MyBatis


MyBatis

环境

  • JDK 1.8
  • MySQL 5.7/8.0
  • Maven 3.6
  • IDEA

回顾

  • JDBC
  • MySQL
  • Java基础
  • Maven
  • Junit

框架:配置文件。最好的方式:看官网

1、简介

1.1、什么是MyBatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

1.2、持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
  • 内存:断电即失
  • 数据库,io文件
  • 生活:冷藏,罐头

为什么需要持久化

  • 有一些对象,不能让他丢掉

  • 内存太贵了

1.3、持久层

DAO, Service, Controller

  • 完成持久化工作的代码块
  • 层界限十分明显

1.4、为什么需要MyBatis

  • 传统的JDBC代码太复杂。自动化
  • 帮助程序猿将数据存入数据库中
  • 不用MyBatis也可以。技术没有高低之分

2、第一个MyBatis程序

思路:搭建环境->导入MyBatis->编写代码->测试

2.1、搭建环境

搭建数据库

新建项目

  1. 新建普通Maven项目

  2. 删除src目录

  3. 导入Maven依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <dependencies>
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.25</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
    </dependency>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    </dependency>
    </dependencies>

2.2、创建模块

  • 编写MyBatis的核心配置文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <?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="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="zxia09ZTC!@"/>
    </dataSource>
    </environment>
    </environments>
    </configuration>
  • 编写工具类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public class MyBatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
    try {
    //获取SQLSessionFactory对象
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    public static SqlSession getSqlSession() {
    return sqlSessionFactory.openSession();
    }

    }

2.3、编写代码

  • 实体类

  • 接口

    1
    2
    3
    4
    5
    public interface UserDAO {

    List<User> getUserList();

    }
  • 实现类,由原来的Impl.java转为.xml

    1
    2
    3
    4
    5
    <mapper namespace="com.dogegg.DAO.UserDAO">
    <select id="getUserList" resultType="com.dogegg.pojo.User">
    select * fron mybatis.user
    </select>
    </mapper>

2.4、测试

注意点

org.apache.ibatis.binding.BindingException: Type interface com.dogegg.DAO.UserDAO is not known to the MapperRegistry.

MapperRegistry是什么

核心配置文件中注册mappers

  • Junit

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Test
    public void test() {
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    UserDAO mapper = sqlSession.getMapper(UserDAO.class);
    List<User> userList = mapper.getUserList();
    for (User user : userList) {
    System.out.println(user.getId()+user.getName()+user.getPwd());
    }
    sqlSession.close();
    }

3、CRUD

3.1、namespace

namespace中的包名要和接口的包名一致

3.2、select

选择,查询语句

  • id:对应的namespace中的方法名
  • resultType:SQL语句执行的返回值
  • parameterType:参数类型

3.3、Insert

3.4、Update

3.5、Delete

注意点:增删改要提交事务!

3.6、万能Map

假设我们的实体类或者数据库中的表,字段或参数过多,我们应当考虑使用Map

4、配置解析

4.1、核心配置文件

  • mybatis-config.xml
  • MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
1
2
3
4
5
6
7
8
9
10
11
12
13
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

4.2、环境配置

MyBatis 可以配置成适应多种环境

尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境

MyBatis默认的事务管理器是JDBC,连接池:POOLED

4.3、属性

我们可以通过properties属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置

编写一个配置文件

1
2
3
4
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=xxxxxxxxxxx

在核心配置文件中引入

1
<properties resource="db.properties"/>
  • 可以直接引入外部文件
  • 可以在其中增加属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件

4.4、类型别名

  • 类型别名可为 Java 类型设置一个缩写名字
  • 意在降低冗余的全限定类名书写
1
2
3
<typeAliases>
<typeAlias type="com.dogegg.pojo.User" alias="User"/>
</typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

扫描实体类的包,他的默认别名就位这个类的类名,首字母小写

1
2
3
<typeAliases>
<package name="com.dogegg.pojo"/>
</typeAliases>

在实体类少的时候,用第一种,实体类多,用第二种

如果非要改,可以在实体类增加注解:@Alias

4.5、设置

4.6、其他配置

  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
    • mybatis-generator-core
    • mybatis-plus
    • 通用mapper

4.7、映射器

MapperRegistry:注册绑定我们的mapper文件

方式一:

1
2
3
<mappers>
<mapper resource="com/dogegg/DAO/mapper/UserMapper.xml"/>
</mappers>

方式二:使用class文件绑定注册

注意点:

  • 接口和他的配置文件必须同名
  • 必须在同一个包下

方式三:使用扫描包进行绑定

4.8、生命周期

生命周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder:

  • 一旦创建了SqlSessionFactory,就不再需要它了

SqlSessionFactory:

  • 可以想象为:数据库连接池
  • SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建一个实例
  • 因此SqlSessionFactory的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式

SqlSession:

  • 连接到池的一个请求
  • SqlSession的实例不是线程安全的,因此是不能被共享的,所以他的最佳作用域是请求或者方法作用域
  • 用完之后需赶紧关闭,否则资源被占用

这里面的每一个Mapper,就代表一个具体的业务

5、解决属性名和字段名不一致的问题

5.1、问题

数据库中的字段

新建一个项目,拷贝之前的,测试实体类字段不一致的情况

1
2
3
4
5
public class User {
private int id;
private String name;
private String password;
}

测试出现问题:找不到pwd字段

解决方法:

  • 起别名

    1
    2
    3
    <select id="getUserList" resultType="User">
    select id,name,pwd as password from mybatis.user
    </select>

5.2、resultMap

结果集映射

1
2
id name pwd
id name password
1
2
3
4
5
6
7
8
9
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>

<select id="getUserList" resultMap="UserMap">
select * from mybatis.user
</select>
  • resultMap 元素是 MyBatis 中最重要最强大的元素
  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
  • ResultMap 的优秀之处——你完全可以不用显式地配置它们。 虽然上面的例子不用显式配置 ResultMap
  • 如果这个世界总是这么简单就好了

6、日志

6.1、日志工厂

如果一个数据库操作出现了异常,我们需要排错

  • SLF4J
  • LOG4J【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING【掌握】
  • NO_LOGGING

在MyBatis中具体用哪个日志实现,在设置中设定

STDOUT_LOGGING:标准日志输出

在MyBatis核心配置文件中,配置日志

6.2、Log4j

  1. 先导包
  2. log4j.properties
  3. 配置log4j为日志的实现
  4. log4j的使用:直接测试运行

简单使用

  1. 在要使用log4j的地方导入包
  2. 日志对象,参数为当前类的class
  3. 日志级别

7、分页

思考:为什么要分页?

  • 减少数据的处理量

7.1、使用Limit分页

使用MyBatis实现分页,核心SQL

  1. 接口

    1
    List<User> getUserByLimit(Map<String, Object> map);
  2. Mapper.xml

    1
    2
    3
    <select id="getUserByLimit" parameterType="map" resultType="User">
    select * from mybatis.user limit ${startIndex}, ${pageSize}
    </select>
  3. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @Test
    public void getUserByLimit() {
    SqlSession sqlSession = MyBatisUtils.getSqlSession();
    UserDAO mapper = sqlSession.getMapper(UserDAO.class);
    HashMap<String, Object> stringObjectHashMap = new HashMap<>();
    stringObjectHashMap.put("startIndex",0);
    stringObjectHashMap.put("pageSize",2);
    List<User> userByLimit = mapper.getUserByLimit(stringObjectHashMap);
    System.out.println(userByLimit);
    sqlSession.close();
    }

7.2、RowBounds分页(了解)

不再使用SQL实现分页

  1. 接口
  2. mapper
  3. 测试

7.3、分页插件

8、注解开发

8.1、面向接口编程

解耦

8.2、使用注解开发

  1. 注解在接口上实现
1
2
3
4
5
package org.mybatis.example;
public interface BlogMapper {
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
}
  1. 需要在核心配置文件中绑定接口
  2. 测试

本质:反射机制

底层:动态代理

MyBatis详细的执行流程

MyBatis执行流程

8.3、使用注解CRUD

我们可以在工具类创建的时候实现自动提交事务

方法存在多个参数,所有的参数前面必须加上@Param注解

注意

一定要把接口注册到核心配置文件中

关于@Param注解

  • 基本类型的参数或String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型,可以忽略,但建议都加上
  • 我们在SQL中引用的就是注解中设定的属性

9、Lombok

  • java library
  • plugs
  • build tools
  • annotation

使用步骤

  1. 在IDEA中安装Lombok
  2. 在项目中导入Lombok
  3. 在实体类中加注解
1
2
3
@Data
@AllArgsConstructor
@NoArgsConstructor

10、多对一处理

多对一:

  • 多个学生,对应一个老师
  • 对于学生而言,关联——>多个学生关联一个老师
  • 对于老师而言,集合——>一个老师有很多学生

测试环境搭建

  1. 新建实体类Teacher,Student
  2. 建立Mapper接口
  3. 建立Mapper.xml
  4. 在核心配置文件中绑定注册我们的Mapper接口或者文件
  5. 测试查询是否能成功

按照查询嵌套处理

1
2
3
4
5
6
7
8
9
10
11
12
13
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javatype="Teacher" select="getTeacher"/>
</resultMap>

<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>

<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>

按照结果嵌套处理

1
2
3
4
5
6
7
8
9
10
11
12
13
<select id="getStudent" resultMap="StudentTeacher">
select s.id sid, s.name sname, t.name tname
from student s, teacher t
where s.tid=t.id
</select>

<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher"javatype="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>

回顾MySQL多对一查询方式

  • 子查询
  • 联表查询

11、一对多

比如:一个老师有多个学生

对于老师而言,就是一对多的关系

小结

  1. 关联:association 多对一

  2. 集合:collection 一对多

  3. javaType & ofType

    1. javaType用来指定实体类中属性的类型
    2. ofType用来指定映射到List或集合中的pojo类型,泛型中的约束类型

注意点

  • 保证SQL的可读性
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志

12、动态SQL

什么是动态SQL:根据不同的条件生成不同的SQL语句

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

搭建环境

创建一个基础工程

  1. 导包

  2. 编写配置文件

  3. 编写实体类

    1
    2
    3
    4
    5
    6
    7
    8
    @Data
    public class Blog {
    private int id;
    private String title;
    private String author;
    private Date gmtCreated;
    private int views;
    }
  4. 编写实体类对应的Mapper接口和Mapper.xml文件

IF

1
2
3
4
5
6
7
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog where author='Doge'
<if test="title!=null">
and title=#{title}
</if>
and views > 5000
</select>

Choose(when, otherwise)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author !=null">
author=#{author}
</when>
<otherwise>
views>50000
</otherwise>
</choose>
</where>
</select>

Trim(where, set)

1
2
3
4
5
6
7
8
9
10
11
12
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!= null">
author=#{author}
</if>
</set>
where views>50000
</update>
1
2
3
<trim prefix="SET" suffixOverrides=",">
...
</trim>

动态SQL本质还是SQL语句,只是我们可以在SQL层面增加逻辑代码

SQL片段

有的时候,我们可能会将一些公共的部分抽取出来,方便复用

  1. 使用SQL标签抽取公共的部分

    1
    2
    3
    4
    5
    <sql id="title-not-null">
    <if test="title!=null">
    title=#{title},
    </if>
    </sql>
  2. 在需要使用的地方使用include标签即可

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
    <include refid="title-not-null"></include>
    <if test="author!= null">
    author=#{author}
    </if>
    </set>
    where views>50000
    </update>

注意事项:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

Foreach

1
2
3
4
5
6
7
8
9
<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>

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合即可

建议:

  • 先在MySQL中写出完整的SQL,再改为动态SQL

13、缓存(了解)


文章作者: ZDogEgg
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 ZDogEgg !