一、简介
1.1 MyBatis介绍
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集。
1.2 MyBatis发展史
MyBatis 原本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis ,2013年11月迁移到Github。
<!--more-->1.3 MyBatis和Hibernate的区别
MyBatis 和 Hibernate 都是优秀的持久化框架,都支持JDBC(Java DataBase Connection)和JTA(Java Transaction API)事务处理。
MyBatis 优点
- 更加轻量级,如果说Hibernate是全自动的框架,MyBatis就是半自动的框架;
- 入门简单,即学即用,并且延续了很好的SQL使用经验;
Hibernate 优点
- 开发简单、高效,不需要编写SQL就可以进行基础的数据库操作;
- 可移植行好,大大降低了MySQL和Oracle之间切换的成本(因为使用了HQL查询,而不是直接写SQL语句);
- 缓存机制上Hibernate也好于MyBatis;
1.4 MyBatis集成方式
Mybatis集成方式分为两种:
- 注解版集成
- XML版本集成
XML版本为老式的配置集成方式,重度集成XML文件,SQL语句也是全部写在XML中的;注解版版本,相对来说比较简约,不需要XML配置,只需要使用注解和代码来操作数据。
二、注解版 MyBatis 集成
开发环境
- MySQL 8.0.12
- Spring Boot 2.0.4
- MyBatis Spring Boot 1.3.2(等于 MyBatis 3.4.6)
- JDK 8
- IDEA 2018.2
MyBatis Spring Boot 是 MyBatis 官方为了集成 Spring Boot 而推出的MyBatis版本。
2.1 添加依赖
设置pom.xml文件,添加如下配置
1<dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4 <version>8.0.12</version> 5</dependency> 6 7<dependency> 8 <groupId>org.mybatis.spring.boot</groupId> 9 <artifactId>mybatis-spring-boot-starter</artifactId> 10 <version>1.3.2</version> 11</dependency>
添加 MySQL 和 MyBatis 支持。
2.2 配置数据库连接
设置application.properties文件,添加如下配置
1# MyBatis 配置 2spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true 3spring.datasource.username=root 4spring.datasource.password=123456 5spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 6mybatis.type-aliases-package=com.hello.springboot.mapper
- spring.datasource.url 数据库连接字符串
- spring.datasource.username 数据库用户名
- spring.datasource.password 数据库密码
- spring.datasource.driver-class-name 驱动类型(注意MySQL 8.0的值是com.mysql.cj.jdbc.Driver和之前不同)
- mybatis.type-aliases-package 配置mapper包名
Mapper文件说明
Mapper是MyBatis的核心,是SQL存储的地方,也是配置数据库映射的地方。
2.3 设置 MapperScan 包路径
直接在启动文件SpringbootApplication.java的类上配置@MapperScan,这样就可以省去,单独给每个Mapper上标识@Mapper的麻烦。
1@SpringBootApplication 2@MapperScan("com.hello.springboot.mapper") 3public class SpringbootApplication { 4 public static void main(String[] args) { 5 SpringApplication.run(SpringbootApplication.class, args); 6 } 7}
2.4 添加代码
为了演示的简洁性,我们不做太多的分层处理了,我们这里就分为:实体类、Mapper接口、Controller类,使用Controller直接调用Mapper接口进行数据持久化处理。
User 类:
1public class User { 2 private Long id; 3 private String name; 4 private int age; 5 private String pwd; 6 //省去set、get方法 7}
UserMapper 接口:
1public interface UserMapper { 2 @Select("select * from user") 3 @Results({ 4 @Result(property = "name", column = "name") 5 }) 6 List<User> getAll(); 7 8 @Select("select * from user where id=#{id}") 9 User getById(Long id); 10 11 @Insert({"insert into user(name,age,pwd) values(#{name},#{age},#{pwd})"}) 12 void install(User user); 13 14 @Update({"update user set name=#{name} where id=#{id}"}) 15 void Update(User user); 16 17 @Delete("delete from user where id=#{id}") 18 void delete(Long id); 19}
可以看出来,所有的SQL都是写在Mapper接口里面的。
Mapper里的注解说明
- @Select 查询注解
- @Result 结果集标识,用来对应数据库列名的,如果实体类属性和数据库属性名保持一致,可以忽略此参数
- @Insert 插入注解
- @Update 修改注解
- @Delete 删除注解
Controller 控制器:
1@RestController 2@RequestMapping("/") 3public class UserController { 4 @Autowired 5 private UserMapper userMapper; 6 @RequestMapping("/") 7 public ModelAndView index() { 8 User user = new User(); 9 user.setAge(18); 10 user.setName("Adam"); 11 user.setPwd("123456"); 12 userMapper.install(user); 13 ModelAndView modelAndView = new ModelAndView("/index"); 14 modelAndView.addObject("count", userMapper.getAll().size()); 15 return modelAndView; 16 } 17}
到此为止,已经完成了MyBatis项目的配置了,可以运行调试了。
注解版GitHub源码:https://github.com/vipstone/springboot-example/tree/master/springboot-mybatis
三、XML 版 MyBatis 集成
3.1 添加依赖
设置pom.xml文件,添加如下配置
1<dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4 <version>8.0.12</version> 5</dependency> 6 7<dependency> 8 <groupId>org.mybatis.spring.boot</groupId> 9 <artifactId>mybatis-spring-boot-starter</artifactId> 10 <version>1.3.2</version> 11</dependency>
添加 MySQL 和 MyBatis 支持。
3.2 配置数据库连接
设置application.properties文件,添加如下配置
1# MyBatis 配置 2spring.datasource.url=jdbc:mysql://172.16.10.79:3306/mytestdb?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true 3spring.datasource.username=root 4spring.datasource.password=123456 5spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 6mybatis.type-aliases-package=com.hello.springboot.entity 7mybatis.config-locations=classpath:mybatis/mybatis-config.xml 8mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
- spring.datasource.url 数据库连接字符串
- spring.datasource.username 数据库用户名
- spring.datasource.password 数据库密码
- spring.datasource.driver-class-name 驱动类型(注意MySQL 8.0的值是com.mysql.cj.jdbc.Driver和之前不同)
- mybatis.type-aliases-package 实体类包路径
- mybatis.config-locations 配置MyBatis基础属性
- mybatis.mapper-locations 配置Mapper XML文件
3.3 设置 MapperScan 包路径
直接在启动文件SpringbootApplication.java的类上配置@MapperScan,这样就可以省去,单独给每个Mapper上标识@Mapper的麻烦。
1@SpringBootApplication 2@MapperScan("com.hello.springboot.mapper") 3public class SpringbootApplication { 4 public static void main(String[] args) { 5 SpringApplication.run(SpringbootApplication.class, args); 6 } 7}
3.4 配置XML文件
本示例设置两个xml文件,在resource/mybatis下的mybatis-config.xml(配置MyBatis基础属性)和在resource/mybatis/mapper下的UserMapper.xml(用户和数据交互的SQL语句)。
mybatis-config.xml
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3 4<configuration> 5 <typeAliases> 6 <typeAlias alias="Integer" type="java.lang.Integer"/> 7 <typeAlias alias="Long" type="java.lang.Long"/> 8 <typeAlias alias="HashMap" type="java.util.HashMap"/> 9 <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap"/> 10 <typeAlias alias="ArrayList" type="java.util.ArrayList"/> 11 <typeAlias alias="LinkedList" type="java.util.LinkedList"/> 12 </typeAliases> 13</configuration>
UserMapper.xml
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 4<!--namespace是命名空间,是mapper接口的全路径--> 5<mapper namespace="com.hello.springboot.mapper.UserMapper"> 6 7 <!--resultMap – 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象--> 8 <resultMap id="userResultMap" type="com.hello.springboot.entity.User"> 9 <id property="name" column="username"></id> 10 </resultMap> 11 12 <!--sql – 可被其他语句引用的可重用语句块--> 13 <sql id="colums"> 14 id,username,age,pwd 15 </sql> 16 17 <select id="findAll" resultMap="userResultMap"> 18 select 19 <include refid="colums" /> 20 from user 21 </select> 22 23 <select id="findById" resultMap="userResultMap"> 24 select 25 <include refid="colums" /> 26 from user 27 where id=#{id} 28 </select> 29 30 <insert id="insert" parameterType="com.hello.springboot.entity.User" > 31 INSERT INTO 32 user 33 (username,age,pwd) 34 VALUES 35 (#{name}, #{age}, #{pwd}) 36 </insert> 37 38 <update id="update" parameterType="com.hello.springboot.entity.User" > 39 UPDATE 40 users 41 SET 42 <if test="username != null">username = #{username},</if> 43 <if test="pwd != null">pwd = #{pwd},</if> 44 username = #{username} 45 WHERE 46 id = #{id} 47 </update> 48 49 <delete id="delete" parameterType="java.lang.Long" > 50 DELETE FROM 51 user 52 WHERE 53 id =#{id} 54 </delete> 55 56</mapper>
SQL 映射文件有很少的几个顶级元素(按照它们应该被定义的顺序):
cache– 给定命名空间的缓存配置。cache-ref– 其他命名空间缓存配置的引用。resultMap– 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。parameterMap– 已废弃!老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除,这里不会记录。sql– 可被其他语句引用的可重用语句块。insert– 映射插入语句update– 映射更新语句delete– 映射删除语句select– 映射查询语句
注意: MyBatis中 config 和 mapper 的 XML 头文件是不一样的。
config 头文件
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
mapper 头文件
1<?xml version="1.0" encoding="UTF-8" ?> 2<!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.5 添加代码
为了演示的便捷性,我们添加3个类用于功能的展示,分别是实体类User.java、mapper接口UserMapper.java和控制器类UserController.java,使用控制器类直接调用UserMapper的方法,进行数据存储和查询。
User.java
1package com.hello.springboot.entity; 2public class User { 3 private Long id; 4 private String name; 5 private int age; 6 private String pwd; 7 //省略set/get方法 8} 9
UserMapper.java
1package com.hello.springboot.mapper; 2import com.hello.springboot.entity.User; 3import java.util.List; 4public interface UserMapper { 5 List<User> findAll(); 6 User findById(Long id); 7 void insert(User user); 8 void update(User user); 9 void delete(Long id); 10}
注意: Mapper里的方法名必须和Mapper XML里的一致,不然会找不到执行的SQL。
UserController.java
1@RestController 2@RequestMapping("/") 3public class UserController { 4 @Resource 5 private UserMapper userMapper; 6 7 @RequestMapping("/") 8 public ModelAndView index() { 9 User user = new User(); 10 user.setAge(18); 11 user.setName("Adam"); 12 user.setPwd("123456"); 13 userMapper.insert(user); 14 ModelAndView modelAndView = new ModelAndView("/index"); 15 modelAndView.addObject("count", userMapper.findAll().size()); 16 return modelAndView; 17 } 18 19}
到此为止,已经完成了MyBatis项目的配置了,可以运行调试了。
XML版GitHub:https://github.com/vipstone/springboot-example/tree/master/springboot-mybatis-xml
四、总结
到目前为止我们已经掌握了MyBatis的两种集成方式,注解集成和XML集成,注解版更符合程序员的代码书写习惯,适用于简单快速查询;XML版可以灵活的动态调整SQL,更适合大型项目开发,具体的选择还要看开发场景以及个人喜好了。