项目代码:
mybatis下载地址:https://github.com/mybatis/mybatis-3/
mybatis中文文档地址:http://www.mybatis.org/mybatis-3/zh/
一、简介
• MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。
• MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
• MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录
二、使用mybatis的原因
1、MyBatis是一个半自动化的持久化层框架。
2、JDBC – SQL夹在Java代码块里,耦合度高导致硬编码内伤
- 维护不易且实际开发需求中sql是有变化,频繁修改的情况多见
3、Hibernate和JPA – 长难复杂SQL,对于Hibernate而言处理也不容易
- –内部自动生产的SQL,不容易做特殊优化。
- 基于全映射的全自动框架,大量字段的POJO进行部分映射时比较困难。 导致数据库性能下降。
4、对开发人员而言,核心sql还是需要自己优化
5、sql和java编码分开,功能边界清晰,一个专注业务、 一个专注数据
三、mybatis的简单实现
1、目标分析
配置mybatis,实现mysql数据库与java的简单查询操作。
2、环境配置
(1)maven配置
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
(2)mybatis全局配置文件配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="Szt4698799770"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis/mapper/EmployeeMapper.xml"/>
</mappers>
</configuration>
其中,<mappers>标签下放置具体的java与sql语句的绑定,sql语句的内容。
3、两种交互的方式
(1)通过SqlSession直接执行映射文件中的sql语句
sql映射文件:
<mapper namespace="Employee">
<select id="selectEmp" resultType="bean.Employee">
select * from employee where id = #{id}
</select>
</mapper>
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis/mybatis_config.xml";
//通过classloader将配置文件转换成字节流
InputStream inputStream = Resources.getResourceAsStream(resource);
//将字节流传入SqlSessionFactory中,生成一个SqlSession的工厂
return new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test1() throws IOException {
//获取SqlSession实例,openSession底层调用openSessionFromDataSource
SqlSession sqlSession = getSqlSessionFactory().openSession();
try {
Employee employee = sqlSession.selectOne("Employee.selectEmp", 1);
System.out.println(employee);
}finally {
sqlSession.close();
}
}
(2)通过接口绑定,为接口创建代理对象
sql映射文件:
<mapper namespace="dao.EmployeeMapper">
<select id="getEmpById" resultType="bean.Employee">
select * from employee where id = #{id}
</select>
</mapper>
该方法定义了一个名为EmployeeMapper的接口,其中包含一个返回值类型为Employee的getEmpById()的方法。
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis/mybatis_config.xml";
//通过classloader将配置文件转换成字节流
InputStream inputStream = Resources.getResourceAsStream(resource);
//将字节流传入SqlSessionFactory中,生成一个SqlSession的工厂
return new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test2() throws IOException {
SqlSession sqlSession = getSqlSessionFactory().openSession();
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = employeeMapper.getEmpById(1);
System.out.println(employee);
sqlSession.close();
}
四、Mybatis参数处理
1.多个参数:
在进行查询操作时,如若查询条件为多个参数,面临的问题是:如何将xml文件的参数与java代码中的参数映射起来。mybatis提供了几种方法。
(1)mybatis提供的map封装机制
在mybatis接收传入的参数时,会将参数封装成为一个map集合。所以在xml文件中,我们指定其key值来绑定。
<select id ="getEmpByIdandLastName" resultType="bean.Employee">
select * from employee where id = #{param1} and lastName = #{param2}
</select>
(2)使用命名参数(常用)
在Mapper接口的函数中,声明参数与xml文件绑定
Mapper:
public Employee getEmpByIdandLastName(@Param("id") Integer id,@Param("lastName") String lastname);
xml:
<select id="getEmpByIdandLastName" resultType="bean.Employee">
select * from employee where id = #{id} and lastName = #{lastName}
</select>
(3)POJO
如果传入参数与业务模型相同,则直接传入POJO
(4)使用自定义map传入多个参数
public Employee getEmpByMap(Map<String,Object> map);
EmployeeMapper employeeMapper = sqlSession.getMapper(dao.EmployeeMapper.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("id",1);
map.put("lastName","chenmanlin");
Employee employee = employeeMapper.getEmpByMap(map);
System.out.println(employee)
Tips:如若传入的参数为数组或Collection集合,我们在xml文件中取值时通过#{list[0]}来取。
五、缓存机制
1.一级缓存
一级缓存存在于SqlSession中,在每个sql会话中都存在一个一级缓存。在没创建一个sql会话时,一级缓存自动打开。在执行查询操作时,一级缓存中有先前的查找记录时,将缓存中的记录返回。
2.二级缓存
二级缓存存在于SqlSessionFactory中,在一个sql会话关闭或提交后,会将一级缓存中的数据存放到SqlSessionFactory中相应命名空间的二级缓存中。
(1)二级缓存的开启的条件:
- 在mybatis的配置文件中添加<setting name = "cacheEnabled" value ="true">
- 在对应的mapper.xml文件中配置二级缓存<cache/>
- 对应的POJO实现序列化
(2)数据查询顺序
在进行查询时,首先对二级缓存中的数据进行查找,再一级缓存。若找不到,最后连接数据库查询。
(3)缓存刷新
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
- 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
- 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
3.第三方缓存
- 导入ehcache包,以及整合包,
- 编写ehcache.xml配置文件
- 配置cache标签 – <cache type= "org.mybatis.caches.ehcache.EhcacheCache"></cache>