Chiriri's blog Chiriri's blog
首页
  • Java

    • JavaSE
    • JavaEE
    • 设计模式
  • Python

    • Python
    • Python模块
    • 机器学习
  • Golang

    • Golang
    • gRPC
  • 服务器

    • Linux
    • MySQL
    • NoSQL
    • Kubernetes
  • 项目

    • 传智健康
    • 畅购商城
  • Hadoop生态

    • Hadoop
    • Zookeeper
    • Hive
    • Flume
    • Kafka
    • Azkaban
    • Hbase
    • Scala
    • Spark
    • Flink
  • 大数据项目

    • 离线数仓
  • 青训营

    • 第四届青训营
  • HTML

    • HTML
    • JavaScript
  • Vue

    • Vue2
    • TypeScript
    • Vue3
    • Uni-APP
  • 数据结构与算法
  • C语言
  • 考研数据结构
  • 计算机组成原理
  • 计算机操作系统
  • Java基础

    • Java基础
    • Java集合
    • JUC
    • JVM
  • 框架

    • Spring
    • Dubbo
    • Spring Cloud
  • 数据库

    • MySQL
    • Redis
    • Elasticesearch
  • 消息队列

    • RabbitMQ
    • RocketMQ
  • 408

    • 计算机网络
    • 操作系统
    • 算法
  • 分类
  • 标签
  • 归档
  • 导航站
GitHub (opens new window)

Iekr

苦逼后端开发
首页
  • Java

    • JavaSE
    • JavaEE
    • 设计模式
  • Python

    • Python
    • Python模块
    • 机器学习
  • Golang

    • Golang
    • gRPC
  • 服务器

    • Linux
    • MySQL
    • NoSQL
    • Kubernetes
  • 项目

    • 传智健康
    • 畅购商城
  • Hadoop生态

    • Hadoop
    • Zookeeper
    • Hive
    • Flume
    • Kafka
    • Azkaban
    • Hbase
    • Scala
    • Spark
    • Flink
  • 大数据项目

    • 离线数仓
  • 青训营

    • 第四届青训营
  • HTML

    • HTML
    • JavaScript
  • Vue

    • Vue2
    • TypeScript
    • Vue3
    • Uni-APP
  • 数据结构与算法
  • C语言
  • 考研数据结构
  • 计算机组成原理
  • 计算机操作系统
  • Java基础

    • Java基础
    • Java集合
    • JUC
    • JVM
  • 框架

    • Spring
    • Dubbo
    • Spring Cloud
  • 数据库

    • MySQL
    • Redis
    • Elasticesearch
  • 消息队列

    • RabbitMQ
    • RocketMQ
  • 408

    • 计算机网络
    • 操作系统
    • 算法
  • 分类
  • 标签
  • 归档
  • 导航站
GitHub (opens new window)
  • JavaSE

  • JavaEE

    • MyBatis
      • ORM
      • 使用
        • Resources 加载资源工具类
        • SqlSessionFactoryBuilder 工厂对象功能类
        • SqlSessionFactory 对象
        • SqlSession
      • 映射配置文件
      • 核心配置文件
      • 数据库连接配置引入
      • 增删改查
      • MyBatis获取参数值的两种方式
        • 单个字面量类型的参数
        • 多个字面量类型的参数
        • map集合类型的参数
        • 实体类类型的参数
        • 使用@Param标识参数
      • MyBatis的各种查询功能
        • 查询一个实体类对象
        • 查询一个list集合
        • 查询单个数据
        • 查询一条数据为map集合
        • 查询多条数据为map集合
      • 特殊SQL的执行
        • 模糊查询
        • 批量删除
        • 动态设置表名
        • 添加功能获取自增的主键
      • 起别名
      • log4j
      • 分层思想
      • 接口代理
        • 源码分析
      • 动态SQL
        • if
        • where
        • trim
        • choose、when、otherwise
        • foreach
        • SQL 片段抽取
      • 获取自增的ID 再插入数据
      • 分页插件
        • 分页插件的使用
        • Pageinfo 封装分页相关参数的功能类
      • 多表操作
        • 一对一
        • 一对多
        • 多对多
        • 分步查询
      • 注解
        • 多表操作
        • 一对一
        • 一对多
        • 多对多
      • SQL 构建
      • MyBatis的缓存
        • MyBatis的一级缓存
        • MyBatis的二级缓存
        • 二级缓存的相关配置
        • MyBatis缓存查询的顺序
        • 整合第三方缓存EHCache
      • MyBatis的逆向工程
        • QBC查询
      • 拦截处理器
    • Jackson
    • Jedis
    • Maven
    • POI
    • Spring
    • Spring MVC
    • Maven 高级
    • Dubbo
    • Zookeeper
    • Spring Security
    • Spring Boot
    • Spring Boot 高级
    • RabbitMQ
    • RabbitMQ 高级
    • Spring Cloud
    • Docker
    • ElasticSearch
    • ElasticSearch 高级
  • Linux

  • MySQL

  • NoSQL

  • Python

  • Python模块

  • 机器学习

  • 设计模式

  • 传智健康

  • 畅购商城

  • 博客项目

  • JVM

  • JUC

  • Golang

  • Kubernetes

  • 硅谷课堂

  • C

  • 源码

  • 神领物流

  • RocketMQ

  • 短链平台

  • 后端
  • JavaEE
Iekr
2021-08-22
目录

MyBatis

# MyBatis

MyBatis 是基于 JAVA 的持久层框架,它内部封装了 JDBC

通过 xml 或者 注解 方式使将要的执行各种 statement 配置起来,并通过 java 对象和 statement 中 SQL 的动态参数进行映射生成最终执行的 SQL 语句

执行完 SQL 语句 并将结果映射为 java 对象返回 使用 ORM 思想解决问题

# ORM

Object Relational Mapping 对象关系映射 持久化数据和实体对象的映射模式

# 使用

导入 mybatis.jar 和 mysql.jar

在 src 下创建映射配置文件 名字无所谓 如这里创建 StudentMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="StudentMapper">
    <select id="any" resultType="com.xxx..xx">
        select * from mysql
    </select>
</mapper>
1
2
3
4
5
6
7
8
9
10

在 src 下创建核心配置文件 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="ie">
<!--        配置名-->
        <environment id="ie">
            
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
<!--                驱动-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

<!--    映射类-->
    <mappers>
<!--        映射类名称-->
        <mapper resource="StudentMapper.xml"/> 
    </mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

创建 mapper

public interface StudentMapper {
    
  int any();
}
1
2
3
4

编码使用

// 读取MyBatis的核心配置文件
InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
// 创建SqlSessionFactoryBuilder 工厂对象,并通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
// 执行映射配置文件的sql语句,通过代理模式创建StudentMapper接口的代理实现类对象
List<Object> objects = sqlSession.selectList("StudentMapper.any");
// 释放资源
sqlSession.close();
is.close();
1
2
3
4
5
6
7
8
9

# Resources 加载资源工具类

  • Resources.getResourceAsStream (String fileName) 通过类加载器返回指定资源的字节输入流 与获取类加载 加载指定资源字节输入流一样

# SqlSessionFactoryBuilder 工厂对象功能类

  • new SqlSessionFactoryBuilder ().build (is); 通过指定资源字节输入流获取 SqlSessionFactory 工厂对象

# SqlSessionFactory 对象

  • openSession () 获取 sqlsession 构建者对象 并开启手动提交事务
  • openSession (boolean auotoCommit) 获取 sqlsession 构建者对象 true 为自动提交事务

# SqlSession

构建者对象接口 用于执行 SQL 管理事务 接口代理

  • selectList (String Statement , object parameter) 执行查询语句 并返回 list 集合
  • selectList (String Statement , object parameter) 执行查询语句 返回一个结果对象
  • inser (String Statement , object parameter) 执行新增语句,返回影响行数
  • update (String Statement , object parameter) 执行修改语句,返回影响行数
  • delete (String Statement , object parameter) 执行删除语句,返回影响行数
  • commit () 提交事务
  • rollback () 回滚事务
  • getMapper(Class <T> cls) 获取指定接口的代理实现类对象
  • close () 释放资源

# 映射配置文件

  • mapper 核心根标签
    • namespace 属性 名称空间
  • select 查询标签
    • id 属性 唯一标识
    • resultType 属性 指定结果映射对象类型 类路径 增删改可以不指定类因为返回的是一个影响行数
    • parameterType 属性 指定参数映射对象类型 指定执行时传递的 parameter 类型
    • SQL 语句获取参数 #{属性名}

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="StudentMapper">
    <select id="any" resultType="com.xxx..xx" parameterType="java.lang.long">
        select * from mysql where id = #{id}
    </select>
        
    <insert id="insert" parameterType="笔记.jdbc.src.Student">

        insert into studen value (#{id},#{name},#{age})
        <!-- 从Student 中传递 id name age属性 -->
    </insert>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 核心配置文件

核心配置文件中的标签必须按照固定的顺序:

<?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根标签-->
<configuration>
     <!--引入properties文件,此时就可以${属性名}的方式访问属性值-->
  <properties resource="jdbc.properties"></properties>
    
    <settings>
    <!--将表中字段的下划线自动转换为驼峰-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <!--开启延迟加载-->
    <setting name="lazyLoadingEnabled" value="true"/>
  </settings>
    
    <typeAliases>
    <!--
      typeAlias:设置某个具体的类型的别名
      属性:
      type:需要设置别名的类型的全类名
      alias:设置此类型的别名,若不设置此属性,该类型拥有默认的别名,即类名且不区分大小
写
      若设置此属性,此时该类型的别名只能使用alias所设置的值
    -->
    <!--<typeAlias type="com.atguigu.mybatis.bean.User"></typeAlias>-->
    <!--<typeAlias type="com.atguigu.mybatis.bean.User" alias="abc">
</typeAlias>-->
    <!--以包为单位,设置改包下所有的类型都拥有默认的别名,即类名且不区分大小写-->
    <package name="com.atguigu.mybatis.bean"/>
  </typeAliases>
    
<!--  environments配置数据库环境  default属性指定使用哪一个-->
    <environments default="ie">
<!--        environment配置数据库环境  id属性唯一标识-->
        <environment id="ie">
<!--            transactionManager事务管理  type属性 采用jdbc默认的事务管理-->
            <transactionManager type="JDBC"></transactionManager>
<!--           dataSource数据源信息  type属性 连接池    -->
            <dataSource type="POOLED">
<!--                property连接数据库的配置信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

<!--    mappers引入映射配置文件-->
    <mappers>
<!--        mapper 引入指定的映射配置 resource属性 指定映射配置文件的名名称-->
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

# 数据库连接配置引入

  • <properties> 引入数据库连接配置文件标签
    • resource 属性 数据库连接配置文件路径
  • 获取连接参数
    • ${键名}

application.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mysql
username=root
password=123456
1
2
3
4
<?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根标签-->
<configuration>
<!--  environments配置数据库环境  default属性指定使用哪一个-->
    <properties resource="笔记/mybatis/src/config.properties">
    <environments default="ie">
<!--        environment配置数据库环境  id属性唯一标识-->
        <environment id="ie">
<!--            transactionManager事务管理  type属性 采用jdbc默认的事务管理-->
            <transactionManager type="JDBC"></transactionManager>
<!--           dataSource数据源信息  type属性 连接池    -->
            <dataSource type="POOLED">
<!--                property连接数据库的配置信息-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

<!--    mappers引入映射配置文件-->
    <mappers>
<!--        mapper 引入指定的映射配置 resource属性 指定映射配置文件的名名称-->
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# 增删改查

添加

<!--int insertUser();-->
<insert id="insertUser">
 insert into t_user values(null,'admin','123456',23,'男')
</insert>
1
2
3
4

删除

<!--int deleteUser();-->
<delete id="deleteUser">
 delete from t_user where id = 7
</delete>
1
2
3
4

修改

<!--int updateUser();-->
<update id="updateUser">
 update t_user set username='ybc',password='123' where id = 6
</update>
1
2
3
4

查询一个实体类对象

<!--User getUserById();-->
<select id="getUserById" resultType="com.atguigu.mybatis.bean.User">
 select * from t_user where id = 2
</select>
1
2
3
4

查询集合

<!--List<User> getUserList();-->
<select id="getUserList" resultType="com.atguigu.mybatis.bean.User">
 select * from t_user
</select>
1
2
3
4

查询的标签 select 必须设置属性 resultType 或 resultMap,用于设置实体类和数据库表的映射关系

  • resultType:自动映射,用于属性名和表中字段名一致的情况
  • resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况

当查询的数据为多条时,不能使用实体类作为返回值,只能使用集合,否则会抛出异常 TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值

# MyBatis 获取参数值的两种方式

MyBatis 获取参数值的两种方式:${} 和 #{}

  • ${} 的本质就是字符串拼接
  • #{} 的本质就是占位符赋值

${} 使用字符串拼接的方式拼接 sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是 #{} 使用占位符赋值的方式拼接 sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号

# 单个字面量类型的参数

若 mapper 接口中的方法参数为单个的字面量类型 此时可以使用 ${} 和 #{} 以任意的名称获取参数的值,注意 ${} 需要手动加单引号

# 多个字面量类型的参数

若 mapper 接口中的方法参数为多个时 此时 MyBatis 会自动将这些参数放在一个 map 集合中,以 arg0,arg1... 为键,以参数为值;以 param1,param2... 为键,以参数为值;因此只需要通过 ${} 和 #{} 访问 map 集合的键就可以获取相对应的值,注意 ${} 需要手动加单引号

# map 集合类型的参数

若 mapper 接口中的方法需要的参数为多个时,此时可以手动创建 map 集合,将这些数据放在 map 中只需要通过 ${} 和 #{} 访问 map 集合的键就可以获取相对应的值,注意 ${} 需要手动加单引号

# 实体类类型的参数

若 mapper 接口中的方法参数为实体类对象时 此时可以使用 ${} 和 #{},通过访问实体类对象中的属性名获取属性值,注意 ${} 需要手动加单引号

# 使用 @Param 标识参数

可以通过 @Param 注解标识 mapper 接口中的方法参数 此时,会将这些参数放在 map 集合中,以 @Param 注解的 value 属性值为键,以参数为值;以 param1,param2... 为键,以参数为值;只需要通过 ${} 和 #{} 访问 map 集合的键就可以获取相对应的值,注意 ${} 需要手动加单引号

# MyBatis 的各种查询功能

# 查询一个实体类对象

/**
* 根据用户id查询用户信息
* @param id
* @return
*/
User getUserById(@Param("id") int id);
1
2
3
4
5
6
<!--User getUserById(@Param("id") int id);-->
<select id="getUserById" resultType="User">
select * from t_user where id = #{id}
</select>
1
2
3
4

# 查询一个 list 集合

/**
* 查询所有用户信息
* @return
*/
List<User> getUserList();
1
2
3
4
5
<!--List<User> getUserList();-->
<select id="getUserList" resultType="User">
 select * from t_user
</select>
1
2
3
4

# 查询单个数据

/**
* 查询用户的总记录数
* @return
* 在MyBatis中,对于Java中常用的类型都设置了类型别名
* 例如:java.lang.Integer-->int|integer
* 例如:int-->_int|_integer
* 例如:Map-->map,List-->list
*/
int getCount();
1
2
3
4
5
6
7
8
9
<!--int getCount();-->
<select id="getCount" resultType="_integer">
 select count(id) from t_user
</select>
1
2
3
4

# 查询一条数据为 map 集合

/**
* 根据用户id查询用户信息为map集合
* @param id
* @return
*/
Map<String, Object> getUserToMap(@Param("id") int id);
1
2
3
4
5
6
<!--Map<String, Object> getUserToMap(@Param("id") int id);-->
<select id="getUserToMap" resultType="map">
select * from t_user where id = #{id}
</select>
<!--结果:{password=123456, sex=男, id=1, age=23, username=admin}-->
1
2
3
4
5

# 查询多条数据为 map 集合

方式一:

/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此
时可以将这些map放在一个list集合中获取
*/
List<Map<String, Object>> getAllUserToMap();
1
2
3
4
5
6
7
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
1
2
3
4

方式二:

/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并
且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的
map集合
*/
@MapKey("id")
Map<String, Object> getAllUserToMap();
1
2
3
4
5
6
7
8
9
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
结果:
<!--
{
  1={password=123456, sex=男, id=1, age=23, username=admin},
  2={password=123456, sex=男, id=2, age=23, username=张三},
  3={password=123456, sex=男, id=3, age=23, username=张三}
}
-->
1
2
3
4
5
6
7
8
9
10
11
12

# 特殊 SQL 的执行

# 模糊查询

/**
* 测试模糊查询
* @param mohu
* @return
*/
List<User> testMohu(@Param("mohu") String mohu);
1
2
3
4
5
6
<!--List<User> testMohu(@Param("mohu") String mohu);-->
<select id="testMohu" resultType="User">
<!--select * from t_user where username like '%${mohu}%'-->
  <!--select * from t_user where username like concat('%',#{mohu},'%')-->
select * from t_user where username like "%"#{mohu}"%"
</select>
1
2
3
4
5
6

# 批量删除

/**
* 批量删除
* @param ids
* @return
*/
int deleteMore(@Param("ids") String ids);
1
2
3
4
5
6
<!--int deleteMore(@Param("ids") String ids);-->
<delete id="deleteMore">
delete from t_user where id in (${ids})
</delete>
1
2
3
4

# 动态设置表名

/**
* 动态设置表名,查询所有的用户信息
* @param tableName
* @return
*/
List<User> getAllUser(@Param("tableName") String tableName);
1
2
3
4
5
6
<!--List<User> getAllUser(@Param("tableName") String tableName);-->
<select id="getAllUser" resultType="User">
 select * from ${tableName}
</select>
1
2
3
4

# 添加功能获取自增的主键

t_clazz(clazz_id,clazz_name) t_student(student_id,student_name,clazz_id)

  1. 添加班级信息
  2. 获取新添加的班级的 id
  3. 为班级分配学生,即将某学的班级 id 修改为新添加的班级的 id
/**
* 添加用户信息
* @param user
* @return
* useGeneratedKeys:设置使用自增的主键
* keyProperty:因为增删改有统一的返回值是受影响的行数,因此只能将获取的自增的主键放在传输的参
数user对象的某个属性中
*/
int insertUser(User user);
1
2
3
4
5
6
7
8
9
<!--int insertUser(User user);-->
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null,#{username},#{password},#{age},#{sex})
</insert>
1
2
3
4

# 起别名

在映射配置中 我们 resultType 属性需要提供 类的全路径 可以在核心配置文件中起别名来简写

  • <typeAliaser> 为全类名起别名的父标签
  • <typeAlias> 为全类名起步名的子标签
    • 属性:
      • type 指定全类名
      • alias 指定别名
  • <package> 为指定包下所有类起别的子标签 别名就是类名
<typeAliases>
    <typeAlias type="笔记.jdbc.src.Student" alias="student"></typeAlias>
</typeAliases>
1
2
3

image-20210822192152234

# log4j

添加依赖

<!-- log4j日志 -->
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.17</version>
</dependency>
1
2
3
4
5
6

加入 log4j 的配置文件 src/main/resources/log4j.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

在核心配置文件添加

<settings>
    <setting name="logImpl" value="log4j"/>
</settings>
1
2
3

并配置好 log4j.properties 配置

# 分层思想

控制层 (controller) ====> 业务层 (service) ====> 持久层 (dao)

持久层 对接数据库

业务层 处理业务逻辑 此处只是暂时直接调用 dao 层的方法

控制层 使用 test 类

# 接口代理

通过接口代理 我们只需要写 dao 层的接口 由 MyBatis 框架根据接口的定义来创建接口的动态代理对象

  • 映射配置文件中的名称空间必须与 dao 层接口的全类名相同
  • 映射配置文件中的增删改查的 id 属性必须和 dao 层接口的方法名相同
  • 映射配置文件中的增删改查标签的 parameterType 属性必须和 dao 层接口方法的参数相同
  • 映射配置文件中的增删改查标签的 resultType 属性必须和 dao 层接口的返回值相同

getMapper(Class <T> cls) 获取指定接口的代理实现类对象

mybatisdemo01 mapper = sqlSession.getMapper(mybatisdemo01.class);
1

# 源码分析

通过 getMapper () 方法 获取到 org.apache.ibatis.binding.MapperProxy 代理对象 底层使用 JDK 的动态代理技术 帮我们实现代理实现类对象

执行方法时调用了 mapperMethod.execute () 方法 通过 switch 语句 判断操作类型是增删改查操作

通过 SqlSession 方法来执行

# 动态 SQL

Mybatis 框架的动态 SQL 技术是一种根据特定条件动态拼装 SQL 语句的功能,它存在的意义是为了解决 拼接 SQL 语句字符串时的痛点问题。可以根据 SQL 语句动态根据条件查询

# if

<if> 条件判断标签 test 属性 条件控制 如果成立则拼接 SQL 语句

if 标签可通过 test 属性的表达式进行判断,若表达式的结果为 true,则标签中的内容会执行;反之标签中 的内容不会执行

<!--List<Emp> getEmpListByMoreTJ(Emp emp);-->
<select id="getEmpListByMoreTJ" resultType="Emp">
 select * from t_emp where 1=1
  <if test="ename != '' and ename != null">
   and ename = #{ename}
  </if>
  <if test="age != '' and age != null">
   and age = #{age}
  </if>
  <if test="sex != '' and sex != null">
   and sex = #{sex}
  </if>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13

# where

<where> 条件标签 如果有动态条件 则使用该标签替代 where 关键字

<select id="getEmpListByMoreTJ2" resultType="Emp">
 select * from t_emp
  <where>
    <if test="ename != '' and ename != null">
     ename = #{ename}
    </if>
    <if test="age != '' and age != null">
     and age = #{age}
    </if>
    <if test="sex != '' and sex != null">
     and sex = #{sex}
    </if>
  </where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

where 和 if 一般结合使用:

  1. 若 where 标签中的 if 条件都不满足,则 where 标签没有任何功能,即不会添加 where 关键字
  2. 若 where 标签中的 if 条件满足,则 where 标签会自动添加 where 关键字,并将条件最前方多余的 and 去掉

注意:where 标签不能去掉条件最后多余的 and

<select id="dongtaisql" resultType="studen">
    select * from stden
    <where>
        <if test="id != null">
            id = #{id}
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
    </where>
</select>
1
2
3
4
5
6
7
8
9
10
11

# trim

trim 用于去掉或添加标签中的内容 常用属性:

  • prefix:在 trim 标签中的内容的前面添加某些内容
  • prefixOverrides:在 trim 标签中的内容的前面去掉某些内容
  • suffix:在 trim 标签中的内容的后面添加某些内容
  • suffixOverrides:在 trim 标签中的内容的后面去掉某些内容
<select id="getEmpListByMoreTJ" resultType="Emp">
 select * from t_emp
  <trim prefix="where" suffixOverrides="and">
    <if test="ename != '' and ename != null">
     ename = #{ename} and
    </if>
    <if test="age != '' and age != null">
     age = #{age} and
    </if>
    <if test="sex != '' and sex != null">
        sex = #{sex}
    </if>
  </trim>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# choose、when、otherwise

choose、when、otherwise 相当于 if...else if..else

<!--List<Emp> getEmpListByChoose(Emp emp);-->
<select id="getEmpListByChoose" resultType="Emp">
 select <include refid="empColumns"></include> from t_emp
  <where>
    <choose>
      <when test="ename != '' and ename != null">
       ename = #{ename}
      </when>
      <when test="age != '' and age != null">
       age = #{age}
      </when>
      <when test="sex != '' and sex != null">
       sex = #{sex}
      </when>
      <when test="email != '' and email != null">
       email = #{email}
      </when>
    </choose>
  </where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# foreach

<foreach> 循环遍历标签 适用于多个参数或者的关系

  • collection:设置要循环的数组或集合
  • open:设置 foreach 标签中的内容的开始符
  • close:设置 foreach 标签中的内容的结束符
  • item:表示集合或数组中的每一个数据
  • separator:设置循环体之间的分隔符
<!-- select * forme studen id in(1,2,3)-->
<select id="selectbyids" resultType="studen" parameterType="list">
    select * from studen
    <where>
        <foreach collection="list" open="id in(" close=")" separator="," item="id">
            #{id}
        </foreach>
    </where>
</select>
1
2
3
4
5
6
7
8
9

# SQL 片段抽取

sql 片段,可以记录一段公共 sql 片段,在使用的地方通过 include 标签进行引入,将一些重复性的 SQL 语句进行抽取 达到复用的效果

  • <sql> 标签 抽取 sql 语句标签 id 属性唯一标识
  • <include> 引入 sql 片段标签 refid 属性需要引用片段的唯一标识
<sql id="select">select * from studen</sql>

<select id="qsq" resultType="student" parameterType="student">
	<include refid="select"></include> where id = #{id}
</select>
1
2
3
4
5

# 获取自增的 ID 再插入数据

先执行 LAST_INSERT_ID () 返回一个 id 并封装在对象 再执行 inser 语句

<insert id="add" parameterType="com.itheima.pojo.CheckGroup">
    <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
        select LAST_INSERT_ID()
    </selectKey>
    insert into t_checkgroup(code, name, sex, helpCode, remark, attention)
    values (#{code}, #{name}, #{sex}, #{helpCode}, #{remark}, #{attention})
</insert>
1
2
3
4
5
6
7

# 分页插件

mybatis 不带分页功能的 mysql 中分页使用 limit 语句 不同的数据库实现的关键字也不同

PageHelper 第三方分页助手

添加依赖

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.2.0</version>
</dependency>
1
2
3
4
5
6

在 MyBatis 的核心配置文件中配置插件

<plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
1
2
3

# 分页插件的使用

在测试类中使用分页功能

PageHelper.startPage(1,3);
// PageHelper.startPage(第几页,每页显示多少个);  设置分页参数
1
2
  • pageNum:当前页的页码
  • pageSize:每页显示的条数

# Pageinfo 封装分页相关参数的功能类

  • getTotal () 获取总条数
  • getPages () 获取总页数
  • getPageNum () 获取当前页
  • getPageSize () 获取每页显示条数
  • getPrePage () 获取上一页
  • getNextPage () 获取下一页
  • islsFiresPage () 获取是否是第一页
  • islsLastPage () 获取是否是最后一页
PageInfo<Student> info =new PageInfo<>(list);
int total = info.getTotal();
1
2

在查询获取 list 集合之后,使用 PageInfo<T> pageInfo = new PageInfo<>(List<T> list, int navigatePages) 获取分页相关数据

  • list:分页之后的数据

  • navigatePages:导航分页的页码数

分页相关数据

PageInfo{
pageNum=8, pageSize=4, size=2, startRow=29, endRow=30, total=30, pages=8,
list=Page{count=true, pageNum=8, pageSize=4, startRow=28, endRow=32, total=30,
pages=8, reasonable=false, pageSizeZero=false},
prePage=7, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true,
hasNextPage=false, navigatePages=5, navigateFirstPage4, navigateLastPage8,
navigatepageNums=[4, 5, 6, 7, 8]
}
1
2
3
4
5
6
7
8
  • pageNum:当前页的页码

  • pageSize:每页显示的条数

  • size:当前页显示的真实条数

  • total:总记录数

  • pages:总页数

  • prePage:上一页的页码

  • nextPage:下一页的页码

  • isFirstPage/isLastPage:是否为第一页 / 最后一页

  • hasPreviousPage/hasNextPage:是否存在上一页 / 下一页

  • navigatePages:导航分页的页码数

  • navigatepageNums:导航分页的页码,[1,2,3,4,5]

# 多表操作

# 一对一

<mapper namespace="1v1">
    <!--
        resultMap 配置字段和实体对象属性的映射关系
        id为唯一标识
        type为映射对象路径 查询的数据要映射的实体类的类型
    -->
    <resultMap id="oneToOne" type="card">
        <!--
            id为主键标签  column为表中列名   property为对象属性名称
            result为其他列标签
        -->
        <id column="cid" property="id"/>
        <result column="number" property="number" />
                <!--
                        association: 配置被包含对象的映射关系   对象内的对象
                        property: 被包含对象的变量名   对象内的对象变量名是什么
                        javaType:被包含对象的数据类型
                -->
        <association property="prs" javaType="person">
            <id column="pid" property="id"></id>
            <result column="name" property="name"/>
            <result column="age" property="age"/>

        </association>
    </resultMap>
        <!--
            resultMap 为多表操作映射
         -->
    <select id="selectall" resultMap="oneToOne">
        select c.id cid,number,pid,name,age from card c,person p where c.pid=p.id;
    </select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  • <resultMap> 配置字段和实体对象属性的映射关系
    • id 属性 唯一标识
    • type 属性 实体对象类型
  • <id> 配置主键映射关系标签
  • <result> 配置非主键映射关系标签
    • column 属性 表中字段名称
    • property 属性 实体对象变量名称
  • <association> 配置被包含对象的映射关系标签
    • property 属性 被包含对象的变量名
    • javaType 属性 被包含对象的数据类型

# 一对多

<mapper>
    <resultMap id="onetomany" type="classes">
        <id column="cid" property="id"/>
        <result column="canem" property="name"/>

        <!--
            collection: 配置被包含的集合对象映射关系
            property属性  被包含集合对象的变量名
            ofType属性  被包含集合对象元素的数据类型
            -->
        <collection property="students" ofType="student">
            <id column="sid" property="id"/>
            <result column="sname" property="name"/>
            <result column="sage" property="age"/>
        </collection>
    </resultMap>
    <select id="selectall" resultMap="onetomany">
        select c.id cid,c.name cname,s.id sid,s.name sname,s.age sage from classes c,student s where c.id=s.id
    </select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • <collection> 配置被包含的集合对象映射关系
    • property 属性 被包含集合对象的变量名
    • ofType 属性 被包含集合对象元素的数据类型

# 多对多

<mapper>
    <resultMap id="manytomany" type="sstdent">
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
        <result column="sage" property="age"/>
        <collection property="coures" ofType="corse">
            <id column="cid" property="id"/>
            <result column="cname" property="name"/>
        </collection>
    </resultMap>
    <select id="selectall" resultMap="manytomany">
        select  sc.sid,s.name sname,s.age sage,sc.cid,c.name cname from stdent s,course c,stu,_cr sc where sc.sid=s.id and sc.cid=c.id
    </select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

<collection> 配置被包含的集合对象映射关系

  • property 属性 被包含集合对象的变量名
  • ofType 属性 被包含集合对象元素的数据类型

# 分步查询

/**
* 通过分步查询查询员工信息
* @param eid
* @return
*/
Emp getEmpByStep(@Param("eid") int eid);
1
2
3
4
5
6
<resultMap id="empDeptStepMap" type="Emp">
    <id column="eid" property="eid"></id>
    <result column="ename" property="ename"></result>
    <result column="age" property="age"></result>
    <result column="sex" property="sex"></result>
    <!--
   select:设置分步查询,查询某个属性的值的sql的标识(namespace.sqlId)
   column:将sql以及查询结果中的某个字段设置为分步查询的条件
    -->
    <association property="dept" select="com.atguigu.MyBatis.mapper.DeptMapper.getEmpDeptByStep" column="did">
</association>
</resultMap>
<!--Emp getEmpByStep(@Param("eid") int eid);-->
<select id="getEmpByStep" resultMap="empDeptStepMap">
select * from t_emp where eid = #{eid}
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

根据员工所对应的部门 id 查询部门信息

/**
* 分步查询的第二步:根据员工所对应的did查询部门信息
* @param did
* @return
*/
Dept getEmpDeptByStep(@Param("did") int did);
1
2
3
4
5
6
<!--Dept getEmpDeptByStep(@Param("did") int did);-->
<select id="getEmpDeptByStep" resultType="Dept">
	select * from t_dept where did = #{did}
</select>
1
2
3
4

分步查询的优点:可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:

  • lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载

  • aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个属性会按需加载

此时就可以实现按需加载,获取的数据是什么,就只会执行相应的 sql。此时可通过 association 和 collection 中的 fetchType 属性设置当前的分步查询是否使用延迟加载,fetchType="lazy (延迟加载)|eager (立即加载)"

# 注解

  • @Select ("查询的 SQL 语句") 指定参数还是 #{key}
  • @Insert ("新增的 SQL 语句") 如:@Insert ("inser into student value (#{id},#{age},#{name})")
  • @Update ("修改的 SQL 语句")
  • @Delete ("删除的 SQL 语句")

通过注解形式的操作 不需要创建映射配置文件 映射配置内容 写在核心配置文件中

<mappers>
    	<!-- name为接口所在的包路径 可以指定类或者指定包下的所有类 -->
        <package name="com.xxx.xxx.stdentmapper"/>
</mappers>
1
2
3
4

# 多表操作

# 一对一

@Select("select * fome card")
    @Results({
            @Result(column = "id" ,property = "id"),
            @Result(column = "number" , property = "number"),
            @Result(
                    property = "p",   // 被包含对象的变量名
                    javaType = Person.class,  // 被包含对象的实现数据类型类
                    column = "pid",  // 根据上面select查询出来表中的哪个字段来查询第二个表
                    /*
                     one = @one()  一对一写法
                     select属性  指定调用哪个接口的哪个方法
                     */
                    one = @One(select = "com.xxx.xxx接口.selectByid方法")
            )
    })
    List<Card> selectAll();

//@one注解调用的接口方法
    @Select("select * from person where id=#{id}")
    Person selectByid(Integer id);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • @Results 封装映射关系的父注解 Result [] vlue () 定义了 Result 数组
    • @Result 封装映射关系的子注解
      • column 属性 查询出的表中字段名称
      • property 属性 实体对象中的属性名称
      • javaType 属性 被包含对象的数据类型
      • one 属性 一对一查询
        • @One 一对一查询注解
          • select 属性 指向要调用某个接口中的方法

# 一对多

//一对多
@Select("select * fome classes")
@Results({
        @Result(column = "id" ,property = "id"),
        @Result(column = "number" , property = "number"),
        @Result(
                property = "students",   // 被包含对象的变量名
                javaType = List.class,  // 被包含对象的实现数据类型类
                column = "id",  // 根据上面select查询出来表中的哪个字段来查询第二个表

        /*                    many = @Many()  一对多写法
                select属性  指定调用哪个接口的哪个方法*/
                many= @Many(select = "com.xxx.xxx接口.xxx方法")
        )
})
List<Classes> selectAll();

//@one注解调用的接口方法
@Select("select * from student where cid=#{cid}")
List<Student> selectByid(Integer cid);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • many 属性 一对多查询
    • @Many 一对多查询注解
      • select 属性 指向要调用某个接口中的方法

# 多对多

//多对多
@Select("select distinct s.id,s.name fome studebt s,stu_cr sc where sc.sid = s.id")
@Results({
        @Result(column = "id" ,property = "id"),
        @Result(column = "number" , property = "number"),
        @Result(
                property = "students",   // 被包含对象的变量名
                javaType = List.class,  // 被包含对象的实现数据类型类
                column = "id",  // 根据上面select查询出来表中的哪个字段来查询第二个表

                /*                  many = @Many()  一对多写法
                select属性  指定调用哪个接口的哪个方法*/
                        many= @Many(select = "com.xxx.xxx接口.xxx方法")
        )
})
List<Student> selectAll();

//@one注解调用的接口方法
@Select("select c.id,c.name from stu_cr sc,course c where sc.cid=c.id and sc.sid=#{id}")
List<Course> selectByid(Integer id);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  • many 属性 一对多查询
    • @Many 一对多查询注解
      • select 属性 指向要调用某个接口中的方法

# SQL 构建

image-20210824191742064

public static void main(String[] args) {
    System.out.println(getSelectall());
    //SELECT *
    //FROM student
}

public static String getSelectall(){
    return new SQL(){
        {
            SELECT("*");
            FROM("student");
        }
    }.toString();

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  • @SelectProvider (type = SQL 构造的类.class , mehod = "要执行类中方法") 查询

  • @InsertProvider ((type = SQL 构造的类.class , mehod = "要执行类中方法") 新增

    public static String getInsert(Student stu){
            return new SQL(){
                {
                    INSERT_INTO("student");
                    INTO_VALUES("#{id},#{age},#{name}");
                }
            }.toString();
    
        }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
  • @UpdateProvider ((type = SQL 构造的类.class , mehod = "要执行类中方法") 更新

  • @DeleteProvider ((type = SQL 构造的类.class , mehod = "要执行类中方法") 删除

# MyBatis 的缓存

# MyBatis 的一级缓存

一级缓存是 SqlSession 级别的,通过同一个 SqlSession 查询的数据会被缓存,下次查询相同的数据,就 会从缓存中直接获取,不会从数据库重新访问

使一级缓存失效的四种情况:

  1. 不同的 SqlSession 对应不同的一级缓存
  2. 同一个 SqlSession 但是查询条件不同
  3. 同一个 SqlSession 两次查询期间执行了任何一次增删改操作
  4. 同一个 SqlSession 两次查询期间手动清空了缓存

# MyBatis 的二级缓存

二级缓存是 SqlSessionFactory 级别,通过同一个 SqlSessionFactory 创建的 SqlSession 查询的结果会被 缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取

二级缓存开启的条件:

a > 在核心配置文件中,设置全局配置属性 cacheEnabled="true",默认为 true,不需要设置

b > 在映射文件中设置标签 <cache />

c > 二级缓存必须在 SqlSession 关闭或提交之后有效

d > 查询的数据所转换的实体类类型必须实现序列化的接口

使二级缓存失效的情况:

两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效

# 二级缓存的相关配置

在 mapper 配置文件中添加的 cache 标签可以设置一些属性:

  • eviction 属性:缓存回收策略,默认的是 LRU。
    • LRU(Least Recently Used) – 最近最少使用的:移除最长时间不被使用的对象。
    • FIFO(First in First out) – 先进先出:按对象进入缓存的顺序来移除它们。
    • SOFT – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
    • WEAK – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
  • flushInterval 属性:刷新间隔,单位毫秒,默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
  • size 属性:引用数目,正整数,代表缓存最多可以存储多少个对象,太大容易导致内存溢出
  • readOnly 属性:只读,true/false
    • true:只读缓存;会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了 很重要的性能优势。
    • false:读写缓存;会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是 false。

# MyBatis 缓存查询的顺序

  • 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
  • 如果二级缓存没有命中,再查询一级缓存
  • 如果一级缓存也没有命中,则查询数据库
  • SqlSession 关闭之后,一级缓存中的数据会写入二级缓存

# 整合第三方缓存 EHCache

添加依赖

<!-- Mybatis EHCache整合包 -->
<dependency>
  <groupId>org.mybatis.caches</groupId>
  <artifactId>mybatis-ehcache</artifactId>
  <version>1.2.1</version>
</dependency>
<!-- slf4j日志门面的一个具体实现 -->
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.2.3</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
jar 包名称 作用
mybatis-ehcache Mybatis 和 EHCache 的整合包
ehcache EHCache 核心包
slf4j-api SLF4J 日志门面包
logback-classic 支持 SLF4J 门面接口的一个具体实现

创建 EHCache 的配置文件 ehcache.xml

<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
  <!-- 磁盘保存路径 -->
  <diskStore path="D:\atguigu\ehcache"/>
 
  <defaultCache
      maxElementsInMemory="1000"
      maxElementsOnDisk="10000000"
      eternal="false"
      overflowToDisk="true"
      timeToIdleSeconds="120"
      timeToLiveSeconds="120"
      diskExpiryThreadIntervalSeconds="120"
      memoryStoreEvictionPolicy="LRU">
  </defaultCache>
</ehcache>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

设置二级缓存的类型

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
1

加入 logback 日志

存在 SLF4J 时,作为简易日志的 log4j 将失效,此时我们需要借助 SLF4J 的具体实现 logback 来打印日志。 创建 logback 的配置文件 logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
  <!-- 指定日志输出的位置 -->
  <appender name="STDOUT"
    class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <!-- 日志输出的格式 -->
      <!-- 按照顺序分别是:时间、日志级别、线程名称、打印日志的类、日志主体内容、换行 -
->
      <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger]
[%msg]%n</pattern>
    </encoder>
  </appender>
 
  <!-- 设置全局日志级别。日志级别按顺序分别是:DEBUG、INFO、WARN、ERROR -->
  <!-- 指定任何一个日志级别都只打印当前级别和后面级别的日志。 -->
  <root level="DEBUG">
    <!-- 指定打印日志的appender,这里通过“STDOUT”引用了前面配置的appender -->
    <appender-ref ref="STDOUT" />
  </root>
 
  <!-- 根据特殊需求指定局部日志级别 -->
  <logger name="com.atguigu.crowd.mapper" level="DEBUG"/>
 
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

EHCache 配置文件说明

属性名 是否必须 作用
maxElementsInMemory 是 在内存中缓存的 element 的最大数目
maxElementsOnDisk 是 在磁盘上缓存的 element 的最大数目,若是 0 表示无穷大
eternal 是 设定缓存的 elements 是否永远不过期。如果为 true,则缓存的数据始终有效,如果为 false 那么还要根据 timeToIdleSeconds、timeToLiveSeconds 判断
overflowToDisk 是 设定当内存缓存溢出的时候是否将过期的 element 缓存到磁盘上
timeToIdleSeconds 否 当缓存在 EhCache 中的数据前后两次访问的时间超过 timeToIdleSeconds 的属性取值时,这些数据便会删除,默认值是 0, 也就是可闲置时间无穷大
timeToLiveSeconds 否 缓存 element 的有效生命期,默认是 0., 也就是 element 存活时间无穷大
diskSpoolBufferSizeMB 否 DiskStore (磁盘缓存) 的缓存区大小。默认是 30MB。每个 Cache 都应该有自己的一个缓冲区
diskPersistent 否 在 VM 重启的时候是否启用磁盘保存 EhCache 中的数据,默认是 false。
diskExpiryThreadIntervalSeconds 否 磁盘缓存的清理线程运行间隔,默认是 120 秒。每个 120s,相应的线程会进行一次 EhCache 中数据的清理工作
memoryStoreEvictionPolicy 否 当内存缓存达到最大,有新的 element 加入的时候,移除缓存中 element 的策略。默认是 LRU(最近最少使用),可选的有 LFU(最不常使用)和 FIFO(先进先出)

# MyBatis 的逆向工程

  • 正向工程:先创建 Java 实体类,由框架负责根据实体类生成数据库表。Hibernate 是支持正向工程 的。
  • 逆向工程:先创建数据库表,由框架负责根据数据库表,反向生成如下资源:
    • Java 实体类
    • Mapper 接口
    • Mapper 映射文件

添加依赖和插件

<!-- 依赖MyBatis核心包 -->
<dependencies>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
  </dependency>
</dependencies>
 
<!-- 控制Maven在构建过程中相关配置 -->
<build>
   
  <!-- 构建过程中用到的插件 -->
  <plugins>
   
    <!-- 具体插件,逆向工程的操作是以构建过程中插件形式出现的 -->
    <plugin>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-maven-plugin</artifactId>
      <version>1.3.0</version>
 
      <!-- 插件的依赖 -->
      <dependencies>
       
        <!-- 逆向工程的核心依赖 -->
        <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.2</version>
        </dependency>
         
        <!-- 数据库连接池 -->
        <dependency>
          <groupId>com.mchange</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.2</version>
        </dependency>
         
        <!-- MySQL驱动 -->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.8</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

创建 MyBatis 的核心配置文件

创建逆向工程的配置文件,文件名必须是: generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
	PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
  <!--
      targetRuntime: 执行生成的逆向工程的版本
          MyBatis3Simple: 生成基本的CRUD(清新简洁版)
          MyBatis3: 生成带条件的CRUD(奢华尊享版)
  -->
  <context id="DB2Tables" targetRuntime="MyBatis3Simple">
    <!-- 数据库的连接信息 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/mybatis"
            userId="root"
            password="123456">
    </jdbcConnection>
    <!-- javaBean的生成策略-->
    <javaModelGenerator targetPackage="com.atguigu.mybatis.bean"
targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <!-- SQL映射文件的生成策略 -->
    <sqlMapGenerator targetPackage="com.atguigu.mybatis.mapper"
 targetProject=".\src\main\resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>
    <!-- Mapper接口的生成策略 -->
    <javaClientGenerator type="XMLMAPPER"
targetPackage="com.atguigu.mybatis.mapper"  targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
    <!-- 逆向分析的表 -->
    <!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
    <!-- domainObjectName属性指定生成出来的实体类的类名 -->
    <table tableName="t_emp" domainObjectName="Emp"/>
    <table tableName="t_dept" domainObjectName="Dept"/>
  </context>
</generatorConfiguration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

执行 MBG 插件的 generate 目标

image-20231208173120609

效果

image-20231208173128960

# QBC 查询

@Test
public void testMBG() throws IOException {
  InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
  SqlSession sqlSession = new
SqlSessionFactoryBuilder().build(is).openSession(true);
  EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
  EmpExample empExample = new EmpExample();
  //创建条件对象,通过andXXX方法为SQL添加查询添加,每个条件之间是and关系
 empExample.createCriteria().andEnameLike("a").andAgeGreaterThan(20).andDidIsNot
Null();
  //将之前添加的条件通过or拼接其他条件
  empExample.or().andSexEqualTo("男");
  List<Emp> list = mapper.selectByExample(empExample);
  for (Emp emp : list) {
    System.out.println(emp);
 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 拦截处理器

有时候我们数据库存储的时间戳,在给前端数据时我们需要转成时间戳并映射到类中,并且我们是列表查询如果一条数据在 serve 层进行解析并赋值那不是效率很低,此时我们可以使用自定义处理来解析处理。

继承 BaseTypeHandler<> 并实现里面的方法,泛型为将要返回的类型

BigintToDateStringTypeHandler

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BigintToDateStringTypeHandler extends BaseTypeHandler<String> {
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        throw new UnsupportedOperationException("Setting String to BIGINT is not supported.");
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long timestamp = rs.getLong(columnName);
        return convertTimestampToString(timestamp);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long timestamp = rs.getLong(columnIndex);
        return convertTimestampToString(timestamp);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long timestamp = cs.getLong(columnIndex);
        return convertTimestampToString(timestamp);
    }

    private String convertTimestampToString(long timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        return dateFormat.format(date);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

然后,在 MyBatis 的 XML 配置文件中使用自定义类型处理器。假设我们有一个名为 User 的实体类,其中包含一个名为 timestamp 的时间戳属性。以下是一个示例的映射文件:

UserDao.xml

<!-- UserDao.xml -->

<mapper namespace="com.example.dao.UserDao">

  <resultMap id="userResultMap" type="com.example.domain.User">
    <id property="id" column="id"/>
    <result property="username" column="username"/>
    <result property="email" column="email"/>
      <!-- 此处使用我们自定义的处理
			property为实体类属性名称
			column为数据库字段名称
			javaType为将要解析成的类型 即实体类该属性的类型
			typeHandler我们自定义的处理器
 -->
    <result property="timestamp" column="timestamp_column" javaType="java.lang.String" jdbcType="BIGINT" typeHandler="com.example.handler.BigintToDateStringTypeHandler"/>
    <!-- 其他字段的映射 -->
  </resultMap>

  <select id="getUserById" resultMap="userResultMap">
    SELECT id, username, email, timestamp_column
    FROM users
    WHERE id = #{userId}
  </select>

  <!-- 其他 SQL 语句 -->

</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
编辑 (opens new window)
#JavaEE
上次更新: 2025/01/01, 10:09:39
JDBC
Jackson

← JDBC Jackson→

最近更新
01
k8s
06-06
02
进程与线程
03-04
03
计算机操作系统概述
02-26
更多文章>
Theme by Vdoing | Copyright © 2022-2025 Iekr | Blog
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式