MyBatis
简介
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old/ Java Objects,普通老式 Java 对象)为数据库中的记录。
我的第一个Mybatis程序
安装入门
传统构建
要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于类路径(classpath)中即可。
基于Maven构建
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>
IDEA 创建Mybatis项目
创建maven项目
导入相关依赖
<!--导入依赖-->
<dependencies>
<!-- MySQL依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- junit 依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
配置resource映射
将项目中特定的文件目录下(默认的是resource目录下自动映射)的所有的配置文件映射,避免后面的资源映射失败.在项目的pom.xml中配置:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
核心配置文件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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
核心配置文件是一个mybatis项目的总的配置,用于构建SqlSessionBuilder,得到对应的SqlSession对象,在核心配置文件中可以配置开发环境、外部的资源文件、映射、日志、别名以及缓存等
使用属性标签导入外部的配置
db.properties数据库相关配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=
核心配置文件:引入
<properties resource="db.properties"/>
设置别名:
<!-- 指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean-->
<typeAliases>
<package name="com.jason.pojo"/>
</typeAliases>
编写获取SqlSessionFactory的工具类
既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession
实例来直接执行已映射的 SQL 语句
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
// 静态初始块
static {
InputStream inputStream ;
// 获取sqlSessionFactory对象
try {
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
// return sqlSessionFactory.openSession(true);自动提交事务
return sqlSessionFactory.openSession();
}
}
得到SqlSessionFactory的流程
注意:
- 在创建mybatis的核心配置文件时候,注意文件的位置,默认可以放置在src/resource/目录下,自动映射,其他位置需要进行资源文件的映射
编写mapper接口以及对应的映射SQL的xml文件
mapper接口文件
mapper接口对应dao层,里面有对该实体对象的数据操作方法抽象。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private Teacher teacher;
}
映射文件StudentMapper.xml以及StudentMapper.java
public interface StudentMapper {
// 根据id获得学生
Student getStudentById(@Param("id") int id);
}
核心配置文件添加映射文件mapper
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:///
形式的 URL),或类名和包名等。例如:
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
<mapper url="file:///var/mappers/BlogMapper.xml"/>
<mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>
这些配置会告诉 MyBatis 去哪里找映射文件。
这里我们添加如下配置:
<mappers>
<mapper resource="com/jason/mapper/StudentMapper.xml"/>
</mappers>
编写测试
@Test
public void getStudentById(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.getStudentById(100);
sqlSession.commit();
sqlSession.close();
}
IDEA错误
-
原因:编译的版本与JDK不兼容
-
解决方法:
使用标准的日志实现:得到我的第一个Mybatis程序执行结果:
MyBatis中的XML 映射器
MyBatis 的真正强大在于它的语句映射,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近95% 的代码。MyBatis 致力于减少使用成本,让用户能更专注于 SQL 代码。
在Mybatis中,xml映射器可以根据mapper接口的入参自动的获取到参数值,对于简单类型,parameterType
属性值可以省略不写,针对复杂类型的参数,可以通过级联获得。比如:
// 更新学生信息
int updateStudent(@Param("student") Student student);
mapper接口方法传入的为复杂类型Student,存在一个Teacher类型的组合数据,在映射语句中,我们可以通过级联获取到所有的数据。
<update id="updateStudent" parameterType="Student">
update mybatis.student set tid = #{student.teacher.id} where id = #{student.id};
</update>
<!-- #{student.teacher.id} :取得传入student的teacher的id属性值,其他依次类推 -->
select
查询语句是 MyBatis 中最常用的元素之一, MyBatis 的基本原则之一是:**在每个插入、更新或删除操作之间,通常会执行多个查询操作。**因此,MyBatis 在查询和结果映射做了相当多的改进。一个简单查询的 select 元素是非常简单的。
<select id="getStudentById" parameterType="_int" resultType="Student">
select * from mybatis.student where id = #{id};
</select>
select 属性列表
属性 | 描述 |
---|---|
id |
在命名空间中唯一的标识符,可以被用来引用这条语句。 |
parameterType |
将会传入这条语句的参数的类全限定名或别名。这个属性是可选的,因为MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数,默认值为未设置(unset)。 |
resultType |
期望从这条语句中返回结果的类全限定名或别名。 注意,如果返回的是集合,那应该设置为集合包含的类型,而不是集合本身的类型。resultType 和 resultMap 之间只能同时使用一个。 |
resultMap |
对外部 resultMap 的命名引用。结果映射是 MyBatis最强大的特性,如果你对其理解透彻,许多复杂的映射问题都能迎刃而解resultType 和 resultMap 之间只能同时使用一个。 |
flushCache |
将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:false。 |
useCache |
将其设置为 true 后,将会导致本条语句的结果被二级缓存缓存起来,默认值:对 select 元素为 true。 |
timeout |
这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为未设置(unset)(依赖数据库驱动)。 |
fetchSize |
这是一个给驱动的建议值,尝试让驱动程序每次批量返回的结果行数等于这个设置值。 默认值为未设置(unset)(依赖驱动)。 |
statementType |
可选 STATEMENT,PREPARED 或 CALLABLE。这会让 MyBatis 分别使用Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。 |
resultSetType |
FORWARD_ONLY,SCROLL_SENSITIVE, SCROLL_INSENSITIVE 或 DEFAULT(等价于 unset) 中的一个,默认值为 unset (依赖数据库驱动)。 |
databaseId |
如果配置了数据库厂商标识(databaseIdProvider),MyBatis 会加载所有不带 databaseId 或匹配当前 databaseId 的语句;如果带和不带的语句都有,则不带的会被忽略。 |
resultOrdered |
这个设置仅针对嵌套结果 select 语句:如果为true,将会假设包含了嵌套结果集或是分组,当返回一个主结果行时,就不会产生对前面结果集的引用。这就使得在获取嵌套结果集的时候不至于内存不够用。默认值:false 。 |
resultSets |
这个设置仅适用于多结果集的情况。它将列出语句执行后返回的结果集并赋予每个结果集一个名称,多个名称之间以逗号分隔。 |
insert, update 和 delete
Insert, Update, Delete 元素的属性
属性 | 描述 |
---|---|
id |
在命名空间中唯一的标识符,可以被用来引用这条语句。 |
parameterType |
将会传入这条语句的参数的类全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数,默认值为未设置(unset)。 |
parameterMap |
|
flushCache |
将其设置为 true 后,只要语句被调用,都会导致本地缓存和二级缓存被清空,默认值:(对 insert、update 和 delete 语句)true。 |
timeout |
这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为未设置(unset)(依赖数据库驱动)。 |
statementType |
可选 STATEMENT,PREPARED 或 CALLABLE。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。 |
useGeneratedKeys |
(仅适用于 insert 和 update)这会令 MyBatis 使用 JDBC 的getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的自动递增字段),默认值:false。 |
keyProperty |
(仅适用于 insert 和 update)指定能够唯一识别对象的属性,MyBatis 会使用getGeneratedKeys 的返回值或 insert 语句的 selectKey 子元素设置它的值,默认值:未设置(unset )。如果生成列不止一个,可以用逗号分隔多个属性名称。 |
keyColumn |
(仅适用于 insert 和 update)设置生成键值在表中的列名,在某些数据库(像 PostgreSQL)中,当主键列不是表中的第一列的时候,是必须设置的。如果生成列不止一个,可以用逗号分隔多个属性名称。 |
databaseId |
如果配置了数据库厂商标识(databaseIdProvider),MyBatis 会加载所有不带 databaseId 或匹配当前 databaseId 的语句;如果带和不带的语句都有,则不带的会被忽略。 |
实例
insert
<insert id="addStudent" parameterType="Student" >
insert into mybatis.student values (#{student.id},#{student.name},#{student.teacher.id});
</insert>
@Test
public void addStudent(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.addStudent(new Student(106,"jason_chen",new Teacher(100,"yu",null)));
sqlSession.commit();
sqlSession.close();
}
update
<update id="updateStudent" parameterType="Student">
update mybatis.student set tid = #{student.teacher.id} where id = #{student.id};
</update>
@Test
public void updateStudent(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.updateStudent(new Student(106,"jason_chen",new Teacher(101,"yu",null)));
sqlSession.commit();
sqlSession.close();
}
delete
<delete id="deleteStudent" parameterType="_int">
delete from mybatis.student where id = #{id};
</delete>
@Test
public void deleteStudent(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
mapper.deleteStudent(106);
sqlSession.commit();
sqlSession.close();
}
MyBatis的结果映射
resultMap
元素是 MyBatis 中最重要最强大的元素。它可以让你从 90%的 JDBC ResultSets
数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份resultMap
能够代替实现同等功能的数千行代码。ResultMap的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
MyBatis 创建时的一个思想是:数据库不可能永远是你所想或所需的那个样子。我们希望每个数据库都具备良好的第三范式或 BCNF 范式,可惜它们并不都是那样。如果能有一种数据库映射模式,完美适配所有的应用程序,那就太好了,但可惜也没有。而 ResultMap 就是 MyBatis 对这个问题的答案。
解决实体类字段名与数据库列名不一致
结果映射
constructor
- 用于在实例化类时,注入结果到构造方法中idArg
- ID 参数;标记出作为 ID 的结果可以帮助提高整体性能arg
- 将被注入到构造方法的一个普通结果
id
– 一个 b;标记出作为 ID 的结果可以帮助提高整体性能result
– 注入到字段或 JavaBean 属性的普通结果association
– 一个复杂类型的关联;许多结果将包装成这种类型- 嵌套结果映射 – 关联可以是
resultMap
元素,或是对其它结果映射的引用
- 嵌套结果映射 – 关联可以是
collection
– 一个复杂类型的集合- 嵌套结果映射 – 集合可以是
resultMap
元素,或是对其它结果映射的引用
- 嵌套结果映射 – 集合可以是
discriminator
– 使用结果值来决定使用哪个 resultMap- case – 基于某些值的结果映射
- 嵌套结果映射 –
case
也是一个结果映射,因此具有相同的结构和元素;或者引用其它的结果映射
一对多和多对一:collection&association
一个教师对应多个学生,现在有如下需求:
-
查询教师的基本信息,不需要对应的学生集合信息
<select id="getTeacherById" parameterType="_int" resultType="Teacher"> select * from mybatis.teacher where id = #{id}; </select>
利用resultMap可以解决这个问题,结果集映射。
-
查询一位老师所教的所有学生的集合以及教师的姓名
<select id="getStudentsOfTeacher" parameterType="_int" resultMap="StudentsOfTeacher"> select s.id s_id, s.name s_name , t.id t_id , t.name t_name from mybatis.student s , mybatis.teacher t where s.tid = #{tid} and t.id = #{tid}; </select> <resultMap id="StudentsOfTeacher" type="Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> <collection property="students" javaType="ArrayList" ofType="Student" column="Teacher"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> <association property="teacher" javaType="Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </collection> </resultMap>
利用了 resultMap
可以将从从数据库中查询得到的数据项进行拼接,构成需要的数据类型,创建新的对象。针对 Teacher
类,他具有一个 List<Student>
的属性,数据库中没有与之对应的列,我们通过 resultMap
将字段取出,依次进行构造,得到完整的数据。
<collection></collection>
——>针对属性是集合类型的,Teacher
中的Students
为此类型
<association></association>
——针对属性是一个复杂的数据类型,Student
中的 Teacher
为此类型
动态 SQL
动态 SQL 是 MyBatis 的强大特性之一。
他极大的简化了通常的SQL语句的拼接,提高了开发效率。
有三类方式:
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
if
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。
假设需求:从数据库中查出符合要求的博客,传入的参数是可变的。
<select id="getBlog" parameterType="map" resultType="Blog">
select * from blog where 1 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
<if test="create_time != null">
and create_time = #{create_time}
</if>
<if test="views != null">
and views > #{views}
</if>
</select>
可以根据传入的参数自动的拼接SQL语句。但是这个SQL语句还存在问题:where 1 = 1
,问题是我们如果去掉该语句,拼接SQL语句的时候就会出现SQL语法错误。下面的方式就可以解决这个问题。
trim、where、set
使用了 <where/>
就可以不用写 where 1 = 1
:
<select id="getBlog" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
<if test="create_time != null">
and create_time = #{create_time}
</if>
<if test="views != null">
and views > #{views}
</if>
</where>
</select>
where
元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
动态更新语句的类似解决方案叫做 set
:元素可以用于动态包含需要更新的列,忽略其它不更新的列.
该元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">
username=#{username},
</if>
<if test="password != null">
password=#{password},
</if>
<if test="email != null">
email=#{email},
</if>
<if test="bio != null">
bio=#{bio}
</if>
</set>
where id=#{id}
</update>
可以通过自定义 trim
元素来定制 where
或者 set
元素的功能
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
<trim prefix="SET" suffixOverrides=",">
...
</trim>
choose、when、otherwise
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose
元素,它有点像 Java 中的 switch 语句
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
foreach
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
foreach
元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。
提示
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
比如:如果你的数据库还支持多行插入, 你也可以传入一个 Author
数组或集合
<insert id="insertAuthor" useGeneratedKeys="true"
keyProperty="id">
insert into Author (username, password, email, bio) values
<foreach item="item" collection="list" separator=",">
(#{item.username}, #{item.password}, #{item.email}, #{item.bio})
</foreach>
</insert>