MyBatis 的真正强大在于它的语句映射。由于它的异常强大,映射器的 XML 文件就显得相对简单。MyBatis 致力于减少使用成本,让用户能更专注于 SQL 代码。
SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):
顶级元素解释
在每个顶级元素标签中可以添加很多个属性
1、insert、update、delete元素
属性 | 描述 |
---|---|
id | 在命名空间中唯一的标识符,可以被用来引用这条语句。 |
parameterType | 将会传入这条语句的参数的类全限定名或别名。这个属性是可选的,因为 MyBatis 可以通过类型处理器(TypeHandler)推断出具体传入语句的参数,默认值为未设置(unset)。 |
parameterMap | 用于引用外部 parameterMap 的属性,目前已被废弃。请使用行内参数映射和 parameterType 属性。 |
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 的语句;如果带和不带的语句都有,则不带的会被忽略。 |
useGeneratedKeys案例演示
1、导入maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatis_hello</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--1、mybatis依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--2、连接mysql需要数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!--3、测试类-->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--4、log4j打印日志-->
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<!--解决资源过滤问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
2、创建数据库表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT NULL,
`user_name` varchar(16) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4;
3、新建实体类
public class User {
private Integer id;
private Integer age;
private String userName;
private String email;
//set、get
4、新建Dao层
package com.lian.dao;
import com.lian.pojo.User;
public interface UserDao {
Integer addUser(User user);
}
5、新建db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://8.131.84.120:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username=root
password=root
6、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>
<!--引入数据源值-->
<properties resource="db.properties"/>
<!--设置列名映射的时候是否是驼峰标识-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--类型别名-->
<typeAliases>
<typeAlias type="com.lian.pojo.Emp" alias="emp"/>
</typeAliases>
<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>
<!--配置映射xml-->
<mappers>
<mapper class="com.lian.dao.UserDao"/>
</mappers>
</configuration>
7、测试
@Test
public void test5() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
Integer integer = mapper.addUser(new User("dan"));
System.out.println(integer);
sqlSession.commit();
sqlSession.close();
}
2、select
1、参数的取值方式
在xml文件中编写sql语句的时候有两种取值的方式,分别是#{}和${}:
当使用${}
时:
<select id="selectById" resultType="com.lian.pojo.User">
select * from user where id = ${id}
</select>
会造成sql注入
当使用#{}
时:
<select id="selectById" resultType="com.lian.pojo.User">
select * from user where id = #{id}
</select>
查询结果为正常
小结
使用==#{}==方式进行取值:
采用的是参数预编译的方式,参数的位置使用?进行替代,不会出现sql注入的问题
使用==${}==方式进行取值:
采用的是直接跟sql语句进行拼接的方式
2、处理集合返回结果
<!--当返回值的结果是集合的时候,返回值依然是集合中具体的类型-->
<select id="selectAllEmp" resultType="com.lian.bean.Emp">
select * from emp
</select>
<!--在查询的时候可以设置返回值的类型为map,当mybatis查询完成之后会把列的名称作为key
列的值作为value,转换到map中
-->
<select id="selectEmpByEmpReturnMap" resultType="map">
select * from emp where empno = #{empno}
</select>
<!--注意,当返回的结果是一个集合对象的是,返回值的类型一定要写集合具体value的类型
同时在dao的方法上要添加@MapKey的注解,来设置key是什么结果
@MapKey("empno")
Map<Integer,Emp> getAllEmpReturnMap();-->
<select id="getAllEmpReturnMap" resultType="com.mashibing.bean.Emp">
select * from emp
</select>
3、自定义结果集resultMap
<?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="com.lian.dao.DogDao">
<!--
在使用mybatis进行查询的时候,mybatis默认会帮我们进行结果的封装,但是要求列名跟属性名称一一对应上
在实际的使用过程中,我们会发现有时候数据库中的列名跟我们类中的属性名并不是一一对应的,此时就需要起别名
起别名有两种实现方式:
1、在编写sql语句的时候添加别名
2、自定义封装结果集
-->
<!--根据查询的数据进行结果的封装要使用resultMap属性,表示使用自定义规则-->
<select id="selectDogById" resultMap="myDog">
select * from dog where id = #{id}
</select>
<!--自定义结果集,将每一个列的数据跟javaBean的对象属性对应起来
type:表示为哪一个javaBean对象进行对应
id:唯一标识,方便其他属性标签进行引用
-->
<resultMap id="myDog" type="com.lian.bean.Dog">
<!--
指定主键列的对应规则:
column:表示表中的主键列
property:指定javaBean的属性
-->
<id column="id" property="id"></id>
<!--设置其他列的对应关系-->
<result column="dname" property="name"></result>
<result column="dage" property="age"></result>
<result column="dgender" property="gender"></result>
</resultMap>
<!--可以在sql语句中写别名-->
<!-- <select id="selectDogById" resultType="com.lian.bean.Dog">
select id id,dname name,dage age,dgender gender from dog where id = #{id}
</select>-->
<!--这种方式是查询不到任何结果的,因为属性名跟列名并不是一一对应的-->
<!-- <select id="selectDogById" resultType="com.lian.bean.Dog">
select * from dog where id = #{id}
</select>-->
</mapper>
4、联合查询
案例:查询出指定员工id的全部信息
1、创建两张表
emp表
CREATE TABLE `emp` (
`empno` int(10) NOT NULL,
`ename` varchar(20) DEFAULT NULL,
`job` varchar(20) DEFAULT NULL,
`mgr` int(10) DEFAULT NULL,
`hiredate` varchar(20) DEFAULT NULL,
`sal` int(10) DEFAULT NULL,
`comm` int(10) DEFAULT NULL,
`deptno` int(10) DEFAULT NULL,
PRIMARY KEY (`empno`),
KEY `FK_DEPTNO` (`deptno`),
CONSTRAINT `FK_DEPTNO` FOREIGN KEY (`deptno`) REFERENCES `dept` (`deptno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
dept表
CREATE TABLE `dept` (
`deptno` int(10) NOT NULL,
`dname` varchar(20) DEFAULT NULL,
`loc` varchar(20) DEFAULT NULL,
PRIMARY KEY (`deptno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2、生成实体类
emp表
public class Emp {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Integer sal;
private Integer comm;
//private Integer deptno;
private Dept dept;
//set、get
dept表
public class Dept {
private Integer deptno;
private String dname;
private String loc;
//set、get
3、EmpDao
package com.lian.dao;
import com.lian.pojo.Emp;
import org.apache.ibatis.annotations.Param;
public interface EmpDao {
Emp selectByEmpno(@Param("empno") Integer empno);
}
4、EmpDao.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="com.lian.dao.EmpDao">
<!--=============================方式1================================-->
<!--
<select id="selectByEmpno" resultMap="empdept">
select * from emp e
join dept d
on e.deptno = d.deptno
where empno = #{empno}
</select>
<resultMap id="empdept" type="com.lian.pojo.Emp">
<id column="empno" property="empno"/>
<result column="job" property="job"/>
<result column="mgr" property="mgr"/>
<result column="hiredate" property="hiredate"/>
<result column="sal" property="sal"/>
<result column="comm" property="comm"/>
<result column="deptno" property="dept.deptno"/>
<result column="dname" property="dept.dname"/>
<result column="loc" property="dept.loc"/>
</resultMap>
-->
<!--=============================方式2================================-->
<select id="selectByEmpno" resultMap="empdept">
select * from emp e
join dept d
on e.deptno = d.deptno
where empno = #{empno}
</select>
<resultMap id="empdept" type="com.lian.pojo.Emp">
<id column="empno" property="empno"/>
<result column="job" property="job"/>
<result column="mgr" property="mgr"/>
<result column="hiredate" property="hiredate"/>
<result column="sal" property="sal"/>
<result column="comm" property="comm"/>
<association property="dept" javaType="com.lian.pojo.Dept">
<id column="deptno" property="deptno"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
</association>
</resultMap>
</mapper>
5、db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://8.131.84.120:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
username=root
password=root
6、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>
<!--引入数据源值-->
<properties resource="db.properties"/>
<!--设置列名映射的时候是否是驼峰标识-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--类型别名-->
<typeAliases>
<typeAlias type="com.lian.pojo.Emp" alias="emp"/>
</typeAliases>
<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 class="com.lian.dao.EmpDao"/>
</mappers>
</configuration>
7、测试
public class MyTest {
@Test
public void test() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
Emp emp = mapper.selectByEmpno(7369);
System.out.println(emp);
sqlSession.commit();
sqlSession.close();
}
}
返回结果为
DEBUG [main] - ==> Preparing: select * from emp e join dept d on e.deptno = d.deptno where empno = ?
DEBUG [main] - ==> Parameters: 7369(Integer)
TRACE [main] - <== Columns: empno, ename, job, mgr, hiredate, sal, comm, deptno, deptno, dname, loc
TRACE [main] - <== Row: 7369, SMITH, CLERK, 7902, 1980-12-17, 800, null, 20, 20, RESEARCH, DALLAS
DEBUG [main] - <== Total: 1
Emp{empno=7369, ename='null', job='CLERK', mgr=7902, hiredate=Wed Dec 17 00:00:00 CST 1980, sal=800, comm=null, dept=Dept{deptno=20, dname='RESEARCH', loc='DALLAS'}}
Process finished with exit code 0
5、获取集合元素
需求:查询指定部门编号的所有员工信息
注:db.properties等其他文件和内容4一样,记得重新配置mapper映射
1、Dept表
public class Dept {
private Integer deptno;
private String dname;
private String loc;
//1个部门有多个员工
private List<Emp> emps;
2、DeptDao 层
package com.lian.dao;
import com.lian.pojo.Dept;
import org.apache.ibatis.annotations.Param;
public interface DeptDao {
Dept getDeptAndEmp(@Param("deptno") Integer deptno);
}
3、DeptDao.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="com.lian.dao.DeptDao">
<select id="getDeptAndEmp" resultMap="deptEmp">
select * from dept d
join emp e
on d.deptno = e.deptno
where d.deptno = #{deptno}
</select>
<resultMap id="deptEmp" type="com.lian.pojo.Dept">
<id column="deptno" property="deptno"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
<collection property="emps" ofType="com.lian.pojo.Emp">
<id column="empno" property="empno"/>
<result column="job" property="job"/>
<result column="mgr" property="mgr"/>
<result column="hiredate" property="hiredate"/>
<result column="sal" property="sal"/>
<result column="comm" property="comm"/>
</collection>
</resultMap>
</mapper>
4、测试类
@Test
public void test2() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
DeptDao mapper = sqlSession.getMapper(DeptDao.class);
Dept dept = mapper.getDeptAndEmp(10);
System.out.println(dept);
sqlSession.close();
}
返回结果为
DEBUG [main] - ==> Preparing: select * from dept d join emp e on d.deptno = e.deptno where d.deptno = ?
DEBUG [main] - ==> Parameters: 10(Integer)
TRACE [main] - <== Columns: deptno, dname, loc, empno, ename, job, mgr, hiredate, sal, comm, deptno
TRACE [main] - <== Row: 10, ACCOUNTING, NEW YORK, 7782, CLARK, MANAGER, 7839, 1981-06-09, 2450, null, 10
TRACE [main] - <== Row: 10, ACCOUNTING, NEW YORK, 7839, KING, PRESIDENT, null, 1981-11-17, 5000, null, 10
TRACE [main] - <== Row: 10, ACCOUNTING, NEW YORK, 7934, MILLER, CLERK, 7782, 1982-01-23, 1300, null, 10
DEBUG [main] - <== Total: 3
Dept{deptno=10, dname='ACCOUNTING', loc='NEW YORK', emps=[Emp{empno=7782, ename='null', job='MANAGER', mgr=7839, hiredate=Tue Jun 09 00:00:00 CST 1981, sal=2450, comm=null, dept=null}, Emp{empno=7839, ename='null', job='PRESIDENT', mgr=null, hiredate=Tue Nov 17 00:00:00 CST 1981, sal=5000, comm=null, dept=null}, Emp{empno=7934, ename='null', job='CLERK', mgr=7782, hiredate=Sat Jan 23 00:00:00 CST 1982, sal=1300, comm=null, dept=null}]}
Process finished with exit code 0
6、分步查询
需求:查询指定员工id的全部信息
注意:其他内容同上
a、association 关联查询的分步
1、EmpDao层
package com.lian.dao;
import com.lian.pojo.Emp;
import org.apache.ibatis.annotations.Param;
public interface EmpDao {
Emp selectByStep(@Param("empno") Integer empno);
}
2、DeptDao
package com.lian.dao;
import com.lian.pojo.Dept;
import org.apache.ibatis.annotations.Param;
public interface DeptDao {
Dept getDeptByStep(@Param("deptno") Integer deptno);
}
3、EmpDao.xml层
<select id="selectByStep" resultMap="stepEmp">
select * from emp where empno = #{empno}
</select>
<resultMap id="stepEmp" type="com.lian.pojo.Emp">
<id column="empno" property="empno"/>
<result column="job" property="job"/>
<result column="mgr" property="mgr"/>
<result column="hiredate" property="hiredate"/>
<result column="sal" property="sal"/>
<result column="comm" property="comm"/>
<association property="dept" select="com.lian.dao.DeptDao.getDeptByStep" column="deptno"/>
</resultMap>
4、DeptDao.xml
<select id="getDeptByStep" resultType="com.lian.pojo.Dept">
select * from dept where deptno = #{deptno}
</select>
5、测试类
@Test
public void test3() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
Emp emp = mapper.selectByStep(7369);
System.out.println(emp);
sqlSession.close();
}
b、集合collection的分步查询
1、EmpDao 层
package com.lian.dao;
import com.lian.pojo.Emp;
import org.apache.ibatis.annotations.Param;
public interface EmpDao {
Emp selectByStep2(@Param("empno") Integer deptno);
}
2、EmpDao.xml 层
<select id="selectByStep2" resultType="com.lian.pojo.Emp">
select * from emp where deptno = #{deptno}
</select>
3、DeptDao层
public interface DeptDao {
Dept getDeptByStep2(@Param("deptno") Integer deptno);
}
4、DeptDao.xml层
<select id="getDeptByStep2" resultMap="StepDept">
select * from dept where deptno = #{deptno}
</select>
<resultMap id="StepDept" type="com.lian.pojo.Dept">
<id property="deptno" column="deptno"></id>
<result property="dname" column="dname"></result>
<result property="loc" column="loc"></result>
<collection property="emps" ofType="com.lian.pojo.Emp" select="com.lian.dao.EmpDao.selectByStep2" column="deptno"/>
</resultMap>
5、测试
@Test
public void test4() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
DeptDao mapper = sqlSession.getMapper(DeptDao.class);
Dept dept = mapper.getDeptByStep2(10);
System.out.println(dept);
sqlSession.close();
}
3、map
如果实体类或者数据库中的表,字段或参数太多,使用map比较好
1、mapper层
/**
* map
* 1、工作中用的较多,可传任意数量值
*/
void addUser2(Map<String, Object> map);
2、mapper层实现类
<select id="addUser2" parameterType="map">
insert into user(name) values (#{key})
</select>
3、测试
//map应用之查询部分值
@Test
public void test6(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("key","dandan");
mapper.addUser2(map);
sqlSession.close();
}
3、模糊查询
1、mapper层
//模糊查询,根据属性查询
List<User> fuzzyQuery(String value);
//模糊查询,根据map查询
List<User> fuzzyQuery1(Map<String, Object> map);
2、实现类层
<select id="fuzzyQuery" resultType="com.lian.pojo.User" parameterType="string">
select * from user where name like "%"#{value}"%"
</select>
<select id="fuzzyQuery1" resultType="com.lian.pojo.User" parameterType="map">
select * from user where name like "%"#{map}"%"
</select>
3、测试类
//模糊查询,属性传值
@Test
public void test7(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
System.out.println(mapper.fuzzyQuery("张"));
sqlSession.close();
}
//模糊查询,map传值
@Test
public void test8(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("map","张");
List<User> list = mapper.fuzzyQuery1(map);
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
4、配置之属性优化
1、核心配置文件mybatis-config.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
配置前需要先测试成功
演示步骤:
1、配置resource目录下核心文件 mybatis-config.xml
2、配置util包下的 MyBatisUtils
3、配置pojo包下的user类
4、配置dao包下的UserMapper和UserMapper.xml实现类
5、配置测试类
2、环境配置(environments)
MyBatis 可以配置成适应多种环境,例如,开发、测试和生产环境需要有不同的配置
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
<!--默认选择的环境-->
<environments default="development">
<!--开发环境-->
<environment id="development">
<!--默认事务管理器为 JDBC-->
<transactionManager type="JDBC">
<property name="..." value="..."/>
</transactionManager>
<!--默认数据源为 POOLED-->
<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>
<!--测试环境-->
<environment id="test">
</environment>
</environments>
2.1、事务管理器(transactionManager)
在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
- JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
- MANAGED – 这个配置几乎没做什么。
如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器,因为 Spring 模块会使用自带的管理器来覆盖前面的配置。
2.2、数据源(dataSource)
dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源
有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]")
POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间
3、属性(properties)
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。
设置好的属性可以在整个配置文件中用来替换需要动态配置的属性值。
1、db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&UTF-8&serverTimezone=GMT%2B8
username=root
password=root
2、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>
<!--引入外部配置文件-->
<properties resource="db.properties"/>
<!--默认选择环境名称-->
<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>
<!--每一个dao都需要配置映射,有3种方式,class、resource、url-->
<mappers>
<mapper class="com.lian.dao.UserMapper"/>
<!-- <mapper resource="com/lian/dao/userMapper.xml"/>-->
</mappers>
</configuration>
4、类型别名(typeAliases)
类型别名时为java类型设置一个短的名字
存在的意义仅在于用来减少类完全限定名的冗余
<!--给实体类起别名-->
<typeAliases>
<typeAlias type="com.lian.pojo.User" alias="user"/>
</typeAliases>
也可以自定义一个包名,MyBatis会在包名下面搜索需要的java bean,比如:
扫描实体类的包,它的默认别名就为这个类的 类名,首字母小写
<!--给实体类起别名-->
<typeAliases>
<package name="com.lian.pojo"/>
</typeAliases>
实体类比较少的时候,选择第一种方式
如果实体类比较多,选择以整个包的形式起别名
第一种可以Diy起别名,第二种不可以,如果非要改,需要在实体类上加注解,以注解形式起别名
@Alias("user")
public class User implements Serializable {}
5、映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件
方式一:
<!--每一个mapper.xml都需要在MyBatis核心配置文件中注册,有3种方式,class、resource、url-->
<mappers>
<mapper resource="com/lian/dao/userMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<!--每一个dao都需要配置映射,有3种方式,class、resource、url-->
<mappers>
<mapper class="com.lian.dao.UserMapper"/>
</mappers>
注意点:
接口和它的mapper配置文件必须同名
接口和它的mapper配置文件必须在同一个包下
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.lian.dao"/>
</mappers>
6、ResultMap结果集映射
解决属性名和字段名不一致的问题
新建个项目,拷贝之前的,测试实体类字段不一致的情况
1、复制resource下的 db.properties 和 mybatis-config.xml
2、复制 util包下 MyBatisUtils 类
3、复制 pojo包下 User 类
4、复制 dao包下 UserMapper类 和 UserMapper.xml类
5、复制test 类
具体演示:
1、db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&UTF-8&serverTimezone=GMT%2B8
username=root
password=root
2、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>
<!--引入外部配置文件-->
<properties resource="db.properties"/>
<!--别名设置-->
<typeAliases>
<typeAlias type="com.lian.pojo.User" alias="user"/>
<!-- <package name="com.lian.pojo"/>-->
</typeAliases>
<!--默认选择环境名称-->
<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>
<!--每一个dao都需要配置映射,有3种方式,class、resource、url-->
<mappers>
<!-- <mapper class="com.lian.dao.UserMapper"/>-->
<!-- <mapper resource="com/lian/dao/userMapper.xml"/>-->
<package name="com.lian.dao"/>
</mappers>
</configuration>
3、MyBatisUtils
package com.lian.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
/**
* 1、获取sqlSessionFactory
* 2、获取sqlSession
*/
public class MyBatisUtils {
//提升作用域,从局部变量 改为 类变量,随处可用
private static SqlSessionFactory sqlSessionFactory;
/**
* static 作用
* 和类同时加载,初始化static内代码就生成了
* 只生成一次
*/
static {
try {
//使用Mybatis第一步:获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 1、有了 sqlSessionFactory ,就可以获取sqlSession的实例了,sqlSession完全包含了面向数据库执行sql命令所需的全部方法
*/
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
4、User
package com.lian.pojo;
import java.io.Serializable;
/**
* 实体类
*/
//@Alias("user")
public class User implements Serializable {
private int id;
private String name;
private int password;
public User() {
}
public User(final int id, final String name, final int password) {
this.id = id;
this.name = name;
this.password = password;
}
public User(String name, int password) {
this.name=name;
this.password=password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getpassword() {
return password;
}
public void setpassword(int password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password=" + password +
'}';
}
}
5、UserMapper
package com.lian.dao;
import com.lian.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
List<User> queryAll();
User queryOneById(@Param("id") Integer id);
void addUser(User user);
void updateUser(User user);
void deleteUser(@Param("id") Integer id);
}
6、UserMapper.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="com.lian.dao.UserMapper">
<!--结果集映射-->
<resultMap id="test" type="user">
<!--column 数据库中的字段,property 实体类中的属性-->
<result property="password" column="pwd"/>
</resultMap>
<select id="queryAll" resultMap="test">
select * from user
</select>
<select id="queryOneById" resultType="com.lian.pojo.User" parameterType="int">
select * from user where id = #{id}
</select>
<insert id="addUser" parameterType="com.lian.pojo.User">
insert into user(id,name,password) values (#{id},#{name},#{password})
</insert>
<update id="updateUser" parameterType="com.lian.pojo.User">
update user set name=#{name},password=#{password} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id =#{id}
</delete>
</mapper>
7、测试类
package com.lian.dao;
import com.lian.pojo.User;
import com.lian.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class UserMapperTest {
//查询全部用户
@Test
public void test1(){
//1、获取sqlSession对象
SqlSession sqlSession = MyBatisUtils.getSqlSession();
try {
//方式一:getMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.queryAll();
Iterator<User> iterator = users.iterator();
while (iterator.hasNext()){
User next = iterator.next();
System.out.println(next);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
sqlSession.close();
}
}
//根据id查询用户
@Test
public void test2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryOneById(2);
System.out.println(user);
sqlSession.close();
}
//添加用户
@Test
public void test3(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = new ArrayList<User>();
User user1 = new User(1,"dan",110);
User user2 = new User(7,"pi",220);
list.add(user1);
list.add(user2);
list.remove(user1);
list.set(0,new User("ai",666));
list.get(0);
for (User user : list) {
mapper.addUser(user);
}
System.out.println(mapper);
//增删改提交事务,重点!不写的话不会提交到数据库
sqlSession.commit();
sqlSession.close();
}
//修改用户
@Test
public void test4(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(1,"xian",999));
System.out.println(mapper);
//增删改提交事务,重点!不写的话不会提交到数据库
sqlSession.commit();
sqlSession.close();
}
//删除用户
@Test
public void test5(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(1);
System.out.println(mapper);
//增删改提交事务,重点!不写的话不会提交到数据库
sqlSession.commit();
sqlSession.close();
}
}
结果集测试演示
数据库中的字段
实体类User
// User类中的 pwd 改为 password,和数据库中的字段不一致,用resultMap解决
public class User implements Serializable {
private int id;
private String name;
private int password;
结果集映射用法:
<!--结果集映射-->
<resultMap id="test" type="user">
<!--column 数据库中的字段,property 实体类中的属性-->
<result property="password" column="pwd"/>
</resultMap>
<!--查询全部-->
<select id="queryAll" resultMap="test">
select * from user
</select>
7、日志工厂
1、标准日志工厂STDOUT_LOGGING
Mybatis 通过使用内置的日志工厂提供日志功能。内置日志工厂将会把日志工作委托给下面的实现之一:
- SLF4J
- Apache Commons Logging
- Log4j 2
- Log4j
- JDK logging
可选的值有:SLF4J、LOG4J、LOG4J2、JDK_LOGGING、COMMONS_LOGGING、STDOUT_LOGGING、NO_LOGGING,或者是实现了 org.apache.ibatis.logging.Log
接口,且构造方法以字符串为参数的类完全限定名。
<configuration>
<!-- 配置日志 -->
<settings>
...
<!-- 日志父类logimpl value:可实现的子类,包括log4j、slf4j等 -->
<setting name="logImpl" value="LOG4J"/>
...
</settings>
</configuration>
演示案例
<!--配置日志-->
<settings>
<!-- 标准日志工厂实现,不需要导包,其他日志都需要导入包 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
打印结果为
//打开jdbc连接
Opening JDBC Connection
//创建jdbc连接
Created connection 770911223.
//设置自动提交为false,增删改才需要提交事务,查询不需要
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2df32bf7]
==> Preparing: select * from user
==> Parameters:
<== Columns: id, name, pwd
<== Row: 2, 张三, 123456
<== Row: 3, 李四, 123456
<== Row: 4, ai, 666
<== Total: 4
User{id=2, name='张三', password=123456}
User{id=3, name='李四', password=123456}
User{id=4, name='ai', password=666}
User{id=5, name='pi', password=220}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@2df32bf7]
//关闭连接
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2df32bf7]
//将连接返回池
Returned connection 770911223 to pool.
2、log4j日志
8、分页
1、limit分页
1、db.properties
2、mybatis-config.xml
3、mybatistils
4、User
5、UserMapper
public interface UserMapper {
List<User> queryByLimit(Map<String, Object> map);
}
6、UserMapper.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="com.lian.dao.UserMapper">
<resultMap id="test" type="com.lian.pojo.User">
<result property="password" column="pwd"/>
</resultMap>
<select id="queryByLimit" resultMap="test" parameterType="map">
select * from user limit #{startIndex},#{pageSize}
</select>
</mapper>
7、测试类
public class UserMapperTest {
@Test
public void testUser(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("startIndex",1);
map.put("pageSize",2);
List<User> list = mapper.queryByLimit(map);
for (User user : list) {
System.out.println(user);
}
sqlSession.close();
}
}
2、RowBounds分页
1、接口
public interface UserMapper {
List<User> queryByLimit(Map<String, Object> map);
List<User> queryByRowBounds();
}
2、实现类
<?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="com.lian.dao.UserMapper">
<resultMap id="test" type="com.lian.pojo.User">
<result property="password" column="pwd"/>
</resultMap>
<select id="queryByLimit" resultMap="test" parameterType="map">
select * from user limit #{startIndex},#{pageSize}
</select>
<select id="queryByRowBounds" resultMap="test">
select * from user
</select>
</mapper>
3、测试类
@Test
public void testRowBounds(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
RowBounds rowBounds = new RowBounds(2, 2);
List<User> userList = sqlSession.selectList("com.lian.dao.UserMapper.queryByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
3、分页插件PageHelper
网址:https://pagehelper.github.io/
官网如何使用分页插件教程:https://pagehelper.github.io/docs/howtouse/
9、使用注解开发
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o9zUpbbw-1614918735550)(E:\lian_mashibing\视频\shiro8\文档\images\image-20201229123139326.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-u5wwTKVa-1614918735550)(E:\lian_mashibing\视频\shiro8\文档\images\image-20201229123307466.png)]
1、db.properties
2、mybatis-config.xml
3、MyBatisUtils
4、User
5、UserMapper
public interface UserMapper {
@Select("select * from mybatis.user")
List<User> queryAll();
}
6、UserMapper.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="com.lian.dao.UserMapper">
</mapper>
7、测试类
public class UserTest {
@Test
public void test1(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.queryAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
10、注解增删改查CRUD
1、接口
import com.lian.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("select * from mybatis.user")
List<User> queryAll();
//多个参数的时候,一定要加上@Param
@Select("select * from mybatis.user where id = #{id}")
User queryById(@Param("id") Integer id);
@Insert("insert into mybatis.user(id, name, pwd) VALUES (#{id}, #{name} ,#{pwd} )")
void addUser(User user);
@Update("update mybatis.user set name = #{name} where id = #{id} ")
void updateUser(User user);
@Delete("delete from mybatis.user where id = #{id} ")
void deleteUser(@Param("id") Integer id);
}
注意:
#工具类中设置自动提交后,增删改就不需要单独设置 sqlSession.commit 了
sqlSessionFactory.openSession(true);
2、测试类
public class UserTest {
@Test
public void test1(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.queryAll();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void test2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
System.out.println(mapper.queryById(2));
sqlSession.close();
}
//添加
@Test
public void test3(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(12,"dan",111));
//sqlSession.commit();
sqlSession.close();
}
//修改
@Test
public void test4(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(12,"ddd dan",222));
//sqlSession.commit();
sqlSession.close();
}
//删除
@Test
public void test5(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(12);
//sqlSession.commit();
sqlSession.close();
}
11、复杂查询
环境搭建
1、db.properties
2、mybatis-config.xml
3、mybatisUtils
4、学生类
注:数据库设计表时,老师类设置为 tid,外键,这样两个表即可连接查询
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
//无参、有参、set、get、toString
5、老师类
public class Teacher {
private int id;
private String name;
//无参、有参、set、get、toString
6、学生接口
public interface StudentMapper {
}
7、老师接口
public interface TeacherMapper {
@Select("select * from mybatis.teacher where id = #{tid}")
Teacher getTeacher(@Param("tid") int id);
}
8、学生接口实现类,空实现
<?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="com.lian.dao.StudentMapper">
</mapper>
9、老师接口实现类,空实现
<?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="com.lian.dao.TeacherMapper">
</mapper>
10、测试类
public class UserTest1 {
@Test
public void queryTeacher(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
System.out.println(mapper.getTeacher(1));
sqlSession.close();
}
}
1、多对一处理
1、按查询嵌套处理
1、给StudentMapper接口增加方法
//获取所有学生及对应老师的信息
List<Student> getStudents();
2、编写对应的Mapper文件
<?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="com.kuang.mapper.StudentMapper">
<!--
需求:获取所有学生及对应老师的信息
思路:
1. 获取所有学生的信息
2. 根据获取的学生信息的老师ID->获取该老师的信息
3. 思考问题,这样学生的结果集中应该包含老师,该如何处理呢,数据库中我们一般使用关联查询?
1. 做一个结果集映射:StudentTeacher
2. StudentTeacher结果集的类型为 Student
3. 学生中老师的属性为teacher,对应数据库中为tid。
多个 [1,...)学生关联一个老师=> 一对一,一对多
4. 查看官网找到:association – 一个复杂类型的关联;使用它来处理关联查询
-->
<select id="getStudents" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<!--association关联属性 property属性名 javaType属性类型 column在多的一方的表中的列名-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<!--
这里传递过来的id,只有一个属性的时候,下面可以写任何值
association中column多参数配置:
column="{key=value,key=value}"
其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
-->
<select id="getTeacher" resultType="teacher">
select * from teacher where id = #{id}
</select>
</mapper>
3、测试
@Test
public void queryStudent(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudents();
for (Student student : studentList) {
System.out.println(student);
}
sqlSession.close();
}
2、按结果嵌套处理
1、接口方法编写
List<Student> getStudents2();
2、编写对应的mapper文件
<!--
按查询结果嵌套处理
思路:
1. 直接查询出结果,进行结果集的映射
-->
<select id="getStudents2" resultMap="StudentTeacher2" >
select s.id sid, s.name sname , t.name tname
from student s,teacher t
where s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<id property="id" column="sid"/>
<result property="name" column="sname"/>
<!--关联对象property 关联对象在Student实体类中的属性-->
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
2、一对多处理
按结果嵌套处理
1、db.properties
2、mybatis-config.xml
3、MyBatisUtils
设置了sqlSessionFactory.openSession(true); 增删改的测试中就不需要再设置 sqlSession.commit 提交了
4、Teacher
public class Teacher {
private int id;
private String name;
//一个老师多个学生 一对多案例
private List<Student> students;
//无参、有参、set、get、toString
5、Student
6、StudentMapper
7、TeacherMapper
public interface TeacherMapper {
//获取指定老师,及老师下的所有学生
Teacher getTeacher(@Param("id") int id);
}
8、StudentMapper.xml
9、TeacherMapper.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="com.lian.dao.TeacherMapper">
<select id="getTeacher" resultMap="TeacherStudent">
select t.id tid, t.name tname, s.id sid, s.name sname
from teacher t
inner JOIN student s
WHERE s.tid = t.id
and t.id = #{id}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid" />
<result property="name" column="sname" />
<result property="tid" column="tid" />
</collection>
</resultMap>
</mapper>
10、测试类
@Test
public void test2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
按查询嵌套处理
1、TeacherMapper接口编写方法
Teacher getTeacher2(int id);
2、编写接口对应的Mapper配置文件
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id = #{id}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<!--column是一对多的外键 , 写的是一的主键的列名-->
<collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{id}
</select>
3、测试即可
12、动态SQL环境搭建
介绍
什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句.
官网描述:
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
-------------------------------
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
-------------------------------
我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。
搭建环境
新建一个数据库表:blog
字段:id,title,author,create_time,views
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1、db.properties
2、mybatis-config.xml
3、MyBatisUtils 工具类
4、IDUtil 工具类
package com.lian.util;
import java.util.UUID;
public class IDUtil {
public static String genId(){
//javaJDK提供的一个自动生成主键的方法
return UUID.randomUUID().toString().replaceAll("-","");
}
}
5、实体类
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
//set,get....
}
6、编写实体类对应Mapper接口
package com.lian.dao;
import com.lian.pojo.Blog;
public interface BlogMapper {
//新增一个博客
int addBlog(Blog blog);
}
7、Mapper.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="com.lian.dao.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into blog (id, title, author, create_time, views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
</mapper>
8、测试类
public class UserTest3 {
@Test
public void test1(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtil.genId());
blog.setId(IDUtil.genId());
blog.setTitle("Mybatis如此简单");
blog.setAuthor("pipi");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
sqlSession.close();
}
}
12.1、if语句
需求:需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
1、案例:where 1=1
//1、编写接口类 where 1=1
List<Blog> queryByIf1(Map<String, Object> map);
<!-- 2、编写SQL语句 -->
<select id="queryByIf1" resultType="blog" parameterType="map">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
2、案例:where
//1、编写接口类 用 where
List<Blog> queryByIf2(Map<String, Object> map);
<!-- 2、编写SQL语句 -->
<select id="queryByIf2" resultType="blog" parameterType="map">
select * from blog where
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
小结:
这样写我们可以看到,如果 title等于 null,那么查询语句为 select * from user where title=#{title},
但是如果author为空呢?那么查询语句为 select * from user where and author=#{author},
这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!
12.2、where语句
//1、编写接口类 用 <where>
List<Blog> queryByIf3(Map<String, Object> map);
<!-- 2、编写SQL语句 -->
<select id="queryByIf3" resultType="blog" parameterType="map">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
12.3、set语句
同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?
1、编写接口方法
int updateBlog(Map map);
2、sql配置文件 (错误演示)
<update id="updateBySet" parameterType="map">
update blog
set
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
where id = #{id}
</update>
填写作者,不填写标题的情况下,sql打印:update blog set author = ? where id = ? 正确
填写标题,不填写作者的情况下,sql打印:update blog set title = ?, where id = ? 报错
由此得出结论:set 必须要加标签
3、sql配置文件 (正确演示)
<update id="updateBySet" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
小结: 标签会自动去除 后缀的 逗号
12.4、trim语句
1、编写接口方法
//用trim方式自定义实现 <where> 标签
List<Blog> queryByTrimReplaceWhere(Map<String, Object> map);
//用trim方式自定义实现 <set> 标签
int updateByTrimReplaceSet(Map<String, Object> map);
2、sql配置文件
<select id="queryByTrimReplaceWhere" resultType="blog" parameterType="map">
select * from blog
<trim prefix="where" prefixOverrides="and">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</trim>
</select>
<update id="updateByTrimReplaceSet" parameterType="map">
update blog
<trim prefix="set" suffixOverrides=",">
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</trim>
where id = #{id}
</update>
3、测试
@Test
public void test7(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
//map.put("title","炒鸡蛋");
map.put("author","蛋");
mapper.queryByTrimReplaceWhere(map);
sqlSession.close();
}
@Test
public void test8(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
//map.put("title","炒鸡");
//map.put("author","pi");
map.put("id",3);
mapper.updateByTrimReplaceSet(map);
sqlSession.close();
}
12.5、choose 、when、otherwise
1、编写接口方法
List<Blog> queryBlogChoose(Map map);
2、sql配置文件
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="title != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
扩展:
SQL片段
有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
提取SQL片段:
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
引用SQL片段:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>
注意:
①、最好基于 单表来定义 sql 片段,提高片段的可重用性
②、在 sql 片段中不要包括 where
12.6、foreach语句
需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息
1、编写接口
List<Blog> queryBlogForeach(Map map);
2、编写SQL语句
正常sql: select * from blog WHERE 1=1 and ( id = 1 or id = 2 or id =3 )
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from blog where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
小结:其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。
13、缓存
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。 为了使它更加强大而且易于配置,我们对 MyBatis 3 中的缓存实现进行了许多改进。
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:
<cache/>
当添加上该标签之后,会有如下效果:
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
- 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
- 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
在进行配置的时候还会分为一级缓存和二级缓存:
一级缓存:线程级别的缓存,是本地缓存,sqlSession级别的缓存
二级缓存:全局范围的缓存,不止局限于当前会话
1、一级缓存的使用
一级缓存是sqlsession级别的缓存,默认是存在的。在下面的案例中,大家发现我发送了两个相同的请求,但是sql语句仅仅执行了一次,那么就意味着第一次查询的时候已经将结果进行了缓存。
@Test
public void test01() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
List<Emp> list = mapper.selectAllEmp();
for (Emp emp : list) {
System.out.println(emp);
}
System.out.println("--------------------------------");
List<Emp> list2 = mapper.selectAllEmp();
for (Emp emp : list2) {
System.out.println(emp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
}
在大部分的情况下一级缓存是可以的,但是有几种特殊的情况会造成一级缓存失效:
1、一级缓存是sqlSession级别的缓存,如果在应用程序中只有开启了多个sqlsession,那么会造成缓存失效
@Test
public void test02(){
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
List<Emp> list = mapper.selectAllEmp();
for (Emp emp : list) {
System.out.println(emp);
}
System.out.println("================================");
SqlSession sqlSession2 = sqlSessionFactory.openSession();
EmpDao mapper2 = sqlSession2.getMapper(EmpDao.class);
List<Emp> list2 = mapper2.selectAllEmp();
for (Emp emp : list2) {
System.out.println(emp);
}
sqlSession.close();
sqlSession2.close();
}
2、在编写查询的sql语句的时候,一定要注意传递的参数,如果参数不一致,那么也不会缓存结果
3、如果在发送过程中发生了数据的修改,那么结果就不会缓存
@Test
public void test03(){
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
Emp empByEmpno = mapper.findEmpByEmpno(1111);
System.out.println(empByEmpno);
System.out.println("================================");
empByEmpno.setEname("zhangsan");
int i = mapper.updateEmp(empByEmpno);
System.out.println(i);
System.out.println("================================");
Emp empByEmpno1 = mapper.findEmpByEmpno(1111);
System.out.println(empByEmpno1);
sqlSession.close();
}
4、在两次查询期间,手动去清空缓存,也会让缓存失效
@Test
public void test03(){
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
Emp empByEmpno = mapper.findEmpByEmpno(1111);
System.out.println(empByEmpno);
System.out.println("================================");
System.out.println("手动清空缓存");
sqlSession.clearCache();
System.out.println("================================");
Emp empByEmpno1 = mapper.findEmpByEmpno(1111);
System.out.println(empByEmpno1);
sqlSession.close();
}
2、二级缓存
二级缓存是全局作用域缓存,默认是不开启的,需要手动进行配置。
Mybatis提供二级缓存的接口以及实现,缓存实现的时候要求实体类实现Serializable接口,二级缓存在sqlSession关闭或提交之后才会生效。
1、缓存的使用
步骤:
1、全局配置文件中添加如下配置:
<setting name="cacheEnabled" value="true"/>
2、需要在使用二级缓存的映射文件出使用标签标注
3、实体类必须要实现Serializable接口
@Test
public void test04(){
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
EmpDao mapper2 = sqlSession2.getMapper(EmpDao.class);
Emp empByEmpno = mapper.findEmpByEmpno(1111);
System.out.println(empByEmpno);
sqlSession.close();
Emp empByEmpno1 = mapper2.findEmpByEmpno(1111);
System.out.println(empByEmpno1);
sqlSession2.close();
}
2、缓存的属性
eviction:表示缓存回收策略,默认是LRU
LRU:最近最少使用的,移除最长时间不被使用的对象
FIFO:先进先出,按照对象进入缓存的顺序来移除
SOFT:软引用,移除基于垃圾回收器状态和软引用规则的对象
WEAK:弱引用,更积极地移除基于垃圾收集器状态和弱引用规则的对象
flushInternal:刷新间隔,单位毫秒
默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新
size:引用数目,正整数
代表缓存最多可以存储多少个对象,太大容易导致内存溢出
readonly:只读,true/false
true:只读缓存,会给所有调用这返回缓存对象的相同实例,因此这些对象不能被修改。
false:读写缓存,会返回缓存对象的拷贝(序列化实现),这种方式比较安全,默认值
//可以看到会去二级缓存中查找数据,而且二级缓存跟一级缓存中不会同时存在数据,因为二级缓存中的数据是在sqlsession 关闭之后才生效的
@Test
public void test05(){
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
Emp empByEmpno = mapper.findEmpByEmpno(1111);
System.out.println(empByEmpno);
sqlSession.close();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
EmpDao mapper2 = sqlSession2.getMapper(EmpDao.class);
Emp empByEmpno2 = mapper2.findEmpByEmpno(1111);
System.out.println(empByEmpno2);
Emp empByEmpno3 = mapper2.findEmpByEmpno(1111);
System.out.println(empByEmpno3);
sqlSession2.close();
}
// 缓存查询的顺序是先查询二级缓存再查询一级缓存
@Test
public void test05(){
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
Emp empByEmpno = mapper.findEmpByEmpno(1111);
System.out.println(empByEmpno);
sqlSession.close();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
EmpDao mapper2 = sqlSession2.getMapper(EmpDao.class);
Emp empByEmpno2 = mapper2.findEmpByEmpno(1111);
System.out.println(empByEmpno2);
Emp empByEmpno3 = mapper2.findEmpByEmpno(1111);
System.out.println(empByEmpno3);
Emp empByEmpno4 = mapper2.findEmpByEmpno(7369);
System.out.println(empByEmpno4);
Emp empByEmpno5 = mapper2.findEmpByEmpno(7369);
System.out.println(empByEmpno5);
sqlSession2.close();
}
3、二级缓存的作用范围:
如果设置了全局的二级缓存配置,那么在使用的时候需要注意,在每一个单独的select语句中,可以设置将查询缓存关闭,以完成特殊的设置
1、在setting中设置,是配置二级缓存开启,一级缓存默认一直开启
<setting name="cacheEnabled" value="true"/>
2、select标签的useCache属性:
在每一个select的查询中可以设置当前查询是否要使用二级缓存,只对二级缓存有效
3、sql标签的flushCache属性
增删改操作默认值为true,sql执行之后会清空一级缓存和二级缓存,而查询操作默认是false
4、sqlSession.clearCache()
只是用来清楚一级缓存
3、整合第三方缓存
在某些情况下我们也可以自定义实现缓存,或为其他第三方缓存方案创建适配器,来完全覆盖缓存行为。
1、导入对应的maven依赖
<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.8.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.0-alpha1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.0-alpha1</version>
<scope>test</scope>
</dependency>
2、导入ehcache配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘保存路径 -->
<diskStore path="D:\ehcache" />
<defaultCache
maxElementsInMemory="1"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
<!--
属性说明:
l diskStore:指定数据在磁盘中的存储位置。
l defaultCache:当借助CacheManager.add("demoCache")创建Cache时,EhCache便会采用<defalutCache/>指定的的管理策略
以下属性是必须的:
l maxElementsInMemory - 在内存中缓存的element的最大数目
l maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
l eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
l overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上
以下属性是可选的:
l timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
l timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
l diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
l diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
l memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)
-->
3、在mapper文件中添加自定义缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>