MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎全部的 JDBC代码和手动设置参数以及获取结果集。html
MyBatis 本来是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,而且更名为MyBatis ,2013年11月迁移到Github。java
MyBatis 和 Hibernate 都是优秀的持久化框架,都支持JDBC(Java DataBase Connection)和JTA(Java Transaction API)事务处理。mysql
MyBatis 优势git
Hibernate 优势程序员
Mybatis集成方式分为两种:github
XML版本为老式的配置集成方式,重度集成XML文件,SQL语句也是所有写在XML中的;注解版版本,相对来讲比较简约,不须要XML配置,只须要使用注解和代码来操做数据。spring
开发环境sql
MyBatis Spring Boot 是 MyBatis 官方为了集成 Spring Boot 而推出的MyBatis版本。数据库
设置pom.xml文件,添加以下配置apache
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
添加 MySQL 和 MyBatis 支持。
设置application.properties文件,添加以下配置
# MyBatis 配置 spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver mybatis.type-aliases-package=com.hello.springboot.mapper
Mapper文件说明
Mapper是MyBatis的核心,是SQL存储的地方,也是配置数据库映射的地方。
直接在启动文件SpringbootApplication.java的类上配置@MapperScan,这样就能够省去,单独给每一个Mapper上标识@Mapper的麻烦。
@SpringBootApplication @MapperScan("com.hello.springboot.mapper") public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
为了演示的简洁性,咱们不作太多的分层处理了,咱们这里就分为:实体类、Mapper接口、Controller类,使用Controller直接调用Mapper接口进行数据持久化处理。
User 类:
public class User { private Long id; private String name; private int age; private String pwd; //省去set、get方法 }
UserMapper 接口:
public interface UserMapper { @Select("select * from user") @Results({ @Result(property = "name", column = "name") }) List<User> getAll(); @Select("select * from user where id=#{id}") User getById(Long id); @Insert({"insert into user(name,age,pwd) values(#{name},#{age},#{pwd})"}) void install(User user); @Update({"update user set name=#{name} where id=#{id}"}) void Update(User user); @Delete("delete from user where id=#{id}") void delete(Long id); }
能够看出来,全部的SQL都是写在Mapper接口里面的。
Mapper里的注解说明
Controller 控制器:
@RestController @RequestMapping("/") public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/") public ModelAndView index() { User user = new User(); user.setAge(18); user.setName("Adam"); user.setPwd("123456"); userMapper.install(user); ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("count", userMapper.getAll().size()); return modelAndView; } }
到此为止,已经完成了MyBatis项目的配置了,能够运行调试了。
注解版GitHub源码下载:https://github.com/vipstone/springboot-example/tree/master/springboot-mybatis
设置pom.xml文件,添加以下配置
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
添加 MySQL 和 MyBatis 支持。
设置application.properties文件,添加以下配置
# MyBatis 配置 spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver mybatis.type-aliases-package=com.hello.springboot.entity mybatis.config-locations=classpath:mybatis/mybatis-config.xml mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
直接在启动文件SpringbootApplication.java的类上配置@MapperScan,这样就能够省去,单独给每一个Mapper上标识@Mapper的麻烦。
@SpringBootApplication @MapperScan("com.hello.springboot.mapper") public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
本示例设置两个xml文件,在resource/mybatis下的mybatis-config.xml(配置MyBatis基础属性)和在resource/mybatis/mapper下的UserMapper.xml(用户和数据交互的SQL语句)。
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias alias="Integer" type="java.lang.Integer"/> <typeAlias alias="Long" type="java.lang.Long"/> <typeAlias alias="HashMap" type="java.util.HashMap"/> <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/> <typeAlias alias="ArrayList" type="java.util.ArrayList"/> <typeAlias alias="LinkedList" type="java.util.LinkedList"/> </typeAliases> </configuration>
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace是命名空间,是mapper接口的全路径--> <mapper namespace="com.hello.springboot.mapper.UserMapper"> <!--resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象--> <resultMap id="userResultMap" type="com.hello.springboot.entity.User"> <id property="name" column="username"></id> </resultMap> <!--sql – 可被其余语句引用的可重用语句块--> <sql id="colums"> id,username,age,pwd </sql> <select id="findAll" resultMap="userResultMap"> select <include refid="colums" /> from user </select> <select id="findById" resultMap="userResultMap"> select <include refid="colums" /> from user where id=#{id} </select> <insert id="insert" parameterType="com.hello.springboot.entity.User" > INSERT INTO user (username,age,pwd) VALUES (#{name}, #{age}, #{pwd}) </insert> <update id="update" parameterType="com.hello.springboot.entity.User" > UPDATE users SET <if test="username != null">username = #{username},</if> <if test="pwd != null">pwd = #{pwd},</if> username = #{username} WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Long" > DELETE FROM user WHERE id =#{id} </delete> </mapper>
SQL 映射文件有不多的几个顶级元素(按照它们应该被定义的顺序):
cache
– 给定命名空间的缓存配置。cache-ref
– 其余命名空间缓存配置的引用。resultMap
– 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。parameterMap
– 已废弃!老式风格的参数映射。内联参数是首选,这个元素可能在未来被移除,这里不会记录。sql
– 可被其余语句引用的可重用语句块。insert
– 映射插入语句update
– 映射更新语句delete
– 映射删除语句select
– 映射查询语句注意: MyBatis中 config 和 mapper 的 XML 头文件是不同的。
config 头文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
mapper 头文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
Mapper XML 更多配置:http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html
为了演示的便捷性,咱们添加3个类用于功能的展现,分别是实体类User.java、mapper接口UserMapper.java和控制器类UserController.java,使用控制器类直接调用UserMapper的方法,进行数据存储和查询。
User.java
package com.hello.springboot.entity; public class User { private Long id; private String name; private int age; private String pwd; //省略set/get方法 }
UserMapper.java
package com.hello.springboot.mapper; import com.hello.springboot.entity.User; import java.util.List; public interface UserMapper { List<User> findAll(); User findById(Long id); void insert(User user); void update(User user); void delete(Long id); }
注意: Mapper里的方法名必须和Mapper XML里的一致,否则会找不到执行的SQL。
UserController.java
@RestController @RequestMapping("/") public class UserController { @Resource private UserMapper userMapper; @RequestMapping("/") public ModelAndView index() { User user = new User(); user.setAge(18); user.setName("Adam"); user.setPwd("123456"); userMapper.insert(user); ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("count", userMapper.findAll().size()); return modelAndView; } }
到此为止,已经完成了MyBatis项目的配置了,能够运行调试了。
XML版GitHub源码下载:https://github.com/vipstone/springboot-example/tree/master/springboot-mybatis-xml
到目前为止咱们已经掌握了MyBatis的两种集成方式,注解集成和XML集成,注解版更符合程序员的代码书写习惯,适用于简单快速查询;XML版能够灵活的动态调整SQL,更适合大型项目开发,具体的选择还要看开发场景以及我的喜爱了。