MyBatains
1.概念
MyBatis是一个实现了数据持久化的开源框架,简单理解就是对JDBC进行封装。
ORMapping:Object Relationship Mapping 对象关系映射
对象指面向对象
关系指关系型数据库
Java到MySQL的映射,开发者可以以面向对象的思想来管理数据库。
1.优点:
- 减少代码量
- 最简单的持久框架,小巧并且简单易学,解耦合
- 灵活提供xml标签,支持编写动态sql语句
- 提供映射标签,支持对象与数据库的orm字段关系映射
2.缺点:
- sql编写工作量大
- sql依赖数据库,不能随意更换数据库
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WhN0XCH7-1619488735549)(MyBatains.assets/1619271276272.png)]
2.基本使用
-
新建Maven工程,pom.xml中添加依赖
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.6</version> </dependency>
-
新建数据表
USE mybatis; CREATE TABLE t_account( id int PRIMARY key auto_increment, username VARCHAR(11), password VARCHAR(11), age int )
-
新建数据表对应的实体类account
package com.xxx.entity; import lombok.Data; @Data public class Account { private long id; private String username; private String password; private int age; }
-
创建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> <!-- 配置MyBatis的运行环境,可以选择多个运行环境,选取的是id值--> <environments default="development"> <environment id="development"> <!-- 配置事物管理--> <transactionManager type="JDBC"></transactionManager> <!-- POOLED配置JDBC数据源连接池--> <dataSource type="POOLEd"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration>
1.原生接口
1.MyBatis框架需要开发者自定义SQL语句,写在Mapper.xml文件中,实际开发中,会为每个实体类创建对应的Mapper.xml,定义管理该对象的SQL。
<?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">
<!--namespace:mybatis加载配置文件所去找的路径-->
<mapper namespace="com.xxx.mapper.AccountMapper">
<!--parameterType:调用这个方法所要传的参数-->
<insert id="save" parameterType="com.xxx.entity.Account">
insert into t_account(username,password,age) values (#{username},#{password},#{age})
</insert>
</mapper>
- namespace通常设置为文件所在包+文件名的形式
- insert 标签表示添加插入操作
- select 标签表示执行查询操作
- update 标签表示执行跟新操作
- delete标签表示执行删除操作。
- id是实际调用MyBatis方法时需要用到的参数
- parameterType是调用方法时参数的数据类型
2.在全局配置文件config.xml中注册AccountMapper.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>
<!-- 配置MyBatis的运行环境,可以选择多个运行环境,选取的是id值-->
<environments default="development">
<environment id="development">
<!-- 配置事物管理-->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED配置JDBC数据源连接池-->
<dataSource type="POOLEd">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 注册AccountMapper.xml-->
<mappers>
<mapper resource="com/xxx/mapper/AccountMapper.xml"/>
</mappers>
</configuration>
3.调用MyBatis的原生接口执行添加操作
package com.xxx.test;
import com.xxx.entity.Account;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class Test {
public static void main(String[] args) {
//加载myBatis的配置文件
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.xxx.mapper.AccountMapper.save";
Account account = new Account(1,"张三","123456",22);
sqlSession.insert(statement,account);
sqlSession.commit();
}
}
注意要在pom.xml中添加配置
<!-- 让cong.xml读取在java文件下的mapper.xml文件,否则只能读resources下的文件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
2.通过Mapper代理实现自定义接口
1.自定义接口,定义相关业务方法
package com.xxx.repository;
import com.xxx.entity.Account;
import java.util.List;
public interface AccountRepository {
public int save(Account account);
public int update(Account account);
public int deleteById(long id);
public List<Account> findAll(long id);
public Account findById(long id);
}
2.创建接口对应的Mapper.xml,定义接口方法对应的sql语句。
statement标签可根据SQL执行的业务选择insert、delete、update、select。
MyBatis框架会根据规则自动创建接口实现类的代理对象。
规则:
- Mapper.xml中的namespace为接口全类名
- Mapper.xml中statement的id为接口总对应的方法名
- Mapper.xml中staement的parameterType和接口中对应方法的参数类型一致。
- Mapper.xml中statement的result和接口中对应的返回值类型一致
<?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.xxx.repository.AccountRepository">
<!-- insert的返回值一定是int类型,所以不用写-->
<insert id="save" parameterType="com.xxx.entity.Account">
insert into t_account(username,password,age) values (#{username},#{password},#{age})
</insert>
<update id="update" parameterType="com.xxx.entity.Account">
update t_account set username = #{username},password = #{password},age=#{age} where id=#{id}
</update>
<delete id="deleteById" parameterType="long">
delete from t_account where id = #{id}
</delete>
<!-- 写集合里的泛型-->
<select id="findAll" resultType="com.xxx.entity.Account">
select * from t_account
</select>
<select id="findById" parameterType="long" resultType="com.xxx.entity.Account">
select * from t_account where id = #{id}
</select>
</mapper>
3.在config.xml中注册AccountRepository.xml
<!-- 注册AccountRepository.xml-->
<mappers>
<mapper resource="com/xxx/repository/AccountRepository.xml"/>
</mappers>
4.调用接口的代理对象完成相关的业务操作
package com.xxx.test;
import com.xxx.entity.Account;
import com.xxx.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
//加载myBatis的配置文件
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// String statement = "com.xxx.mapper.AccountMapper.save";
// 获取实现接口的代理对象
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
// Account account1 = new Account(2L,"李四","123456",22);
// accountRepository.save(account1);
//必须要提交事物
sqlSession.commit();
// List<Account> list = accountRepository.findAll();
// for (Account account:list) {
// System.out.println(account);
// }
//
// Account account = accountRepository.findById(2);
// System.out.println(account);
// account.setUsername("小明");
// account.setPassword("321");
// int result = accountRepository.update(account);
// sqlSession.commit();
// Account account2 = accountRepository.findById(2);
// System.out.println(account2);
int result = accountRepository.deleteById(2);
sqlSession.commit();
System.out.println(result);
sqlSession.close();
}
}
3.Mapper.xml
-
config.xml,全局配置环境,配置了数据源环境和引入了mapper.xml文件
-
statement标签:select,update,delete,insert分别对应查询,修改,删除,添加操作。
-
parameterType:参数的数据类型
-
基本数据类型,通过id来查询Account
<select id="findById" parameterType="long" resultType="com.xxx.entity.Account"> select * from t_account where id = #{id} </select>
-
String类型,通过name查询Account
<select id="findByName" parameterType="java.lang.String" resultType="com.xxx.entity.Account"> select * from t_account where username = #{username} </select>
-
包装类,通过id来查询Account
<select id="findById2" parameterType="java.lang.Long" resultType="com.xxx.entity.Account"> select * from t_account where id = #{id} </select>
-
多个参数,通name和age查询Account
<!--多个参数,parameterType就不写了,通过下标去获得值--> <select id="findByNameAndAge" resultType="com.xxx.entity.Account"> select * from t_account where username = #{param1} and age = #{param2} </select>
- java Bean
<update id="update" parameterType="com.xxx.entity.Account"> update t_account set username = #{username},password = #{password},age=#{age} where id=#{id} </update>
-
-
结果类型
- 基本数据类型,统计Account总数
<select id="count" resultType="int"> select count(id) from t_account </select>
- 封装类,统计Account的总数
<select id="count2" resultType="java.lang.Integer"> select count(id) from t_account </select>
- String类型,通过id查询的Account的name
<select id="findNameById" resultType="java.lang.String"> select username from t_account where id = #{id} </select>
- java bean
<select id="findById" parameterType="long" resultType="com.xxx.entity.Account"> select * from t_account where id = #{id} </select>
4.级联查询
1.一对多
- Sudent
package com.xxx.entity;
import lombok.Data;
@Data
public class Student {
private long id;
private String name;
private Classess classess;
}
- Classess
package com.xxx.entity;
import lombok.Data;
import java.util.List;
@Data
public class Classess {
private long id;
private String name;
private List<Student> students;
}
- StudentRepository
package com.xxx.repository;
import com.xxx.entity.Student;
public interface StudentRepository {
public Student findById(long id);
}
- StudentRepository.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.xxx.repository.StudentRepository">
<!-- 直接映射解决不了问题,要间接映射-->
<!-- id自定义,type:映射之后的结果-->
<resultMap id="studentMap" type="com.xxx.entity.Student">
<!-- 主键用id,column:所要查询的字段-->
<id column="id" property="id"></id>
<!-- 其他字段用result-->
<result column="name" property="name"></result>
<!-- 一个对象用association-->
<association property="classess" javaType="com.xxx.entity.Classess">
<id column="cid" property="id"></id>
<id column="cname" property="name"></id>
</association>
</resultMap>
<select id="findById" parameterType="long" resultMap="studentMap">
select s.id,s.name,c.id as cid,c.name as cname from student s,classes c where s.id = #{id} and s.cid = c.id
</select>
</mapper>
2.多对一
- ClassessRepositiory
package com.xxx.repository;
import com.xxx.entity.Classess;
public interface ClassesRepository {
public Classess findById(long id);
}
- ClassessRepositiory.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.xxx.repository.ClassesRepository">
<!-- 直接映射解决不了问题,要间接映射-->
<!-- id自定义,type:映射之后的结果-->
<resultMap id="classesMap" type="com.xxx.entity.Classess">
<!-- column:对应数据库的字段;property:是对应java bean的属性名-->
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
<!-- collection:集合的映射,多个对象;ofType:集合里的泛型-->
<collection property="students" ofType="com.xxx.entity.Student">
<id column="id" property="id"></id>
<id column="name" property="name"></id>
</collection>
</resultMap>
<select id="findById" parameterType="long" resultMap="classesMap">
select s.id,s.name,c.id as cid,c.name as cname from student s,classes c where c.id = #{id} and s.cid = c.id
</select>
</mapper>
3.多对多
- Customer
package com.xxx.entity;
import lombok.Data;
import java.util.List;
@Data
public class Customer {
private long id;
private String name;
private List<Goods> goods;
}
- Goods
package com.xxx.entity;
import lombok.Data;
import java.util.List;
@Data
public class Goods {
private long id;
private String name;
private List<Customer> customers;
}
- CustomerRepositoty
package com.xxx.repository;
import com.xxx.entity.Customer;
public interface CustomerRepository {
public Customer findById(long id);
}
- CustomerRepository.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.xxx.repository.CustomerRepository">
<resultMap id="customerMap" type="com.xxx.entity.Customer">
<id column="cid" property="id"></id>
<id column="cname" property="name"></id>
<collection property="goods" ofType="com.xxx.entity.Goods">
<id column="gid" property="id"></id>
<result column="gname" property="name"></result>
</collection>
</resultMap>
<select id="findById" parameterType="long" resultMap="customerMap">
select c.id cid,c.name cname,g.id gid,g.name gname from customer c,goods g,customer_goods cg where c.id = #{id} and c.id = cg.cid and cg.gid = g.id
</select>
</mapper>
5.逆向工程
MyBatis框架需要:实体类、自定义接口、自定义接口对应的Mapper.xml
传统的开发中上述的三个组件需要开发者手动创建、逆向工程可以来自动创建这三个组件,减轻开发者的工作量,提高工作效率。
缺点:
-
逆行工程只能执行一次,重复执行会重复创建对象
-
不能随意改变表的结构,否则就要删除原来的逆向工程,重新运行一次。
具体使用:
MyBatis Generator,简称MBG,是一个专门为MyBatis框架开发者的代码生成器,可以自动生成MyBatis框架所需的实体类、Mapper接口、Mapper.xml,支持基本的CRUD操作,但是一些相对复杂的SQL需要开发者自己来完成。
1.新建Maven工程,pom.xml
<?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>com.xxx</groupId>
<artifactId>myBatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!--代码生成器-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
<!-- 让cong.xml读取在java文件下的mapper.xml文件,否则只能读resources下的文件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
2.创建MBG配置文件generatorConfig.xml
名字可自定义
-
jdbcConnection配置数据库连接信息。
-
javaModelGenerator配置JavaBean的生成策略
-
sqlMapGenerator配置SQL映射生成文件生成策略。
-
javaClientGenerator配置Mapper接口生成策略。
-
table配置目标数据表(table:表名,domainObjectName:javaBean类名)
<?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:必须这样写-->
<!--uerId:用户名-->
<context id="testTables" targetRuntime="MyBatis3">
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"
userId="root"
password="123456">
</jdbcConnection>
<!-- targetPackage:实体类所在的包,会自动创建-->
<javaModelGenerator
targetPackage="com.xxx.entity"
targetProject="./src/main/java">
</javaModelGenerator>
<!-- sql语句的映射-->
<sqlMapGenerator
targetPackage="com.xxx.repository"
targetProject="./src/main/java">
</sqlMapGenerator>
<!-- mapper.xml的映射-->
<javaClientGenerator
type="XMLMAPPER"
targetPackage="com.xxx.repository"
targetProject="./src/main/java">
</javaClientGenerator>
<!--tableName:所要映射的表名
domainObjectName:所对应的实体类-->
<table tableName="t_user" domainObjectName="User"></table>
</context>
</generatorConfiguration>
3.创建Generator执行类
package com.xxx.test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class TestGenerator {
public static void main(String[] args) {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//配置文件路径
String genCig="/generatorConfig.xml";
//把文件转化为一个对象
File configFile = new File(TestGenerator.class.getResource(genCig).getFile());
ConfigurationParser configurationParser = new ConfigurationParser(warnings);
Configuration configuration = null;
try {
configuration = configurationParser.parseConfiguration(configFile);
} catch (IOException e) {
e.printStackTrace();
} catch (XMLParserException e) {
e.printStackTrace();
}
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = null;
try {
myBatisGenerator = new MyBatisGenerator(configuration,callback,warnings);
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
try {
myBatisGenerator.generate(null);
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
6.MyBatis延迟加载
延迟加载也叫懒加载、惰性加载,使用延迟加载可以提高运行效率,针对于数据的持久层的操作,在某些特定情况下去访问特定的数据库,在其他情况下可以不访问某些表,从一定程度上减少了Java应用与数据库的交互次数。
查询学生和班级时,学生和班级在两张不同的表,如果说当前需求只需要获取学生信息,那么查询学生表即可,如果说需要通过学生获取对应的班级信息,则必须查询两张表。
不同的业务需求,需要查询不同的表,根据具体的业务需求来动态减少数据表查询的工作就是延时加载。
- 在config.xml中开启延迟加载
<settings>
<!-- 打印sql语句-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 开启延时加载,默认是关闭的-->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
-
将多表关联查询差分成多个单表查询
- StudentRepository
public Student findByIdLazy(long id);
- StudentRepository.xml
<resultMap id="studentMapLazy" type="com.xxx.entity.Student"> <!-- 主键用id,column:所查询的字段(不一定是数据库里的字段)--> <id column="id" property="id"></id> <!-- 其他字段用result--> <result column="name" property="name"></result> <!-- 整合对象用association--> <association property="classess" javaType="com.xxx.entity.Classess" select="com.xxx.repository.ClassesRepository.findByIdLazy" column="cid"> </association> </resultMap> <select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy"> select * from student where id = #{id} </select>
- ClassessRepository
public Classess findByIdLazy(long id);
- ClassessRepository.xml
<select id="findByIdLazy" parameterType="long" resultType="com.xxx.entity.Classess"> select * from classes where id = #{id} </select>
7.MyBatis缓存
- 什么是MyBatis缓存
使用缓存可以减少Java应用与数据库的交互次数,从而提升程序的运行效率。比如查询出id = 1的对象,第一次查询之后会自动将该对象保存到缓存中,直接从缓存中取出对象即可,无需再次访问数据库。
- MyBatis缓存分类:
1.一级缓存:sqlSession级别,默认开启,且不能关闭。
造作数据库时需要创建SqlSession对象,在对象中有一个HashMap用于存储缓存数据,不同的SqlSession之间的缓存数据区域是互不影响的。
一级缓存的作用域是SqlSession范围的,当在同一个SqlSession中执行相同的SQL语句时,第一次执行完毕的结果保存在缓存中,第二次查询时直接从缓存中获取。
需要注意的是,如果SqlSession执行了DML操作(insert,update,delete),MyBatis必须将缓存清空,已保证数据的准确性。
package com.xxx.test;
import com.xxx.entity.Account;
import com.xxx.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class Test4 {
public static void main(String[] args) {
InputStream inputStream = Test4.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountRepository accountRepository = sqlSession.getMapper(AccountRepository.class);
Account account = accountRepository.findById(1);
System.out.println(account);
sqlSession.close();
SqlSession sqlSession1 = sqlSessionFactory.openSession();
AccountRepository accountRepository1 = sqlSession1.getMapper(AccountRepository.class);
Account account1 = accountRepository1.findById(1);
System.out.println(account1);
sqlSession.close();
}
}
2.二级缓存:Mapper级别,默认关闭,可以开启。
使用二级缓存时,多个SqlSession使用同一个Mapper的SQL语句操作数据库,得到的数据会存在二级缓存区,同样是使用HashMap进行数据存储,相比较与一级缓存,二级缓存范围更大,多个SqlSession可以共用二级缓存,二级缓存时跨SqlSession的。
二级缓存是多个SqlSession共享的,其作用域是Mapper的同一个namespace,不同的SqlSession两次执行相同的namespace下的SQL语句,参数也相等,则第一次执行成功之后会将数据保存到二级缓存中,第二次可直接从二级缓存中取出数据。
1.自带的二级缓存
- config.xml中配置开启二级缓存
<settings>
<!-- 打印sql语句-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 开启延时加载,默认是关闭的-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
- Mapper.xml中配置二级缓存
<!-- 开启二级缓存-->
<cache></cache>
- 实体类实现序列化接口
package com.xxx.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account implements Serializable {
private long id;
private String username;
private String password;
private int age;
}
2.ehcache二级缓存
- pom.xml中添加相关依赖
<!--二级缓存依赖,两个-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.3</version>
</dependency>
- 添加ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation=".">
<!--持久化磁盘路径-->
<diskStore/>
<!--默认缓存设置-->
<defaultCache maxElementsInMemory="1000"
eternal="false"
overflowToDisk="false"
maxElementsOnDisk="10000000"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<!--
<cache name 缓存名唯一标识
maxElementsInMemory="1000" 内存中最大缓存对象数
eternal="false" 是否永久缓存
timeToIdleSeconds="3600" 缓存清除时间 默认是0 即永不过期
timeToLiveSeconds="0" 缓存存活时间 默认是0 即永不过期
overflowToDisk="true" 缓存对象达到最大数后,将其写入硬盘
maxElementsOnDisk="10000" 磁盘最大缓存数
diskPersistent="false" 磁盘持久化
diskExpiryThreadIntervalSeconds="120" 磁盘缓存的清理线程运行间隔
memoryStoreEvictionPolicy="FIFO" 缓存清空策略
FIFO 先进先出
LFU less frequently used 最少使用
LRU least recently used 最近最少使用
/>
-->
</ehcache>
- config.xml中配置开启二级缓存
<settings>
<!-- 打印sql语句-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 开启延时加载,默认是关闭的-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
- Mapper.xml 中配置二级缓存
<!-- 开启二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<!-- 缓存创建之后,最后一次访问缓存的时间至缓存失效的时间间隔-->
<property name="timeToIdleSeconds" value="3600"/>
<!-- 缓存自创建的时间起至失效的时间间隔-->
<property name="timeToLiveSeconds" value="3600"/>
<!-- 缓存回收策略,LRU表示移除近期使用最少的对象-->
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
- 实体类不需要实现序列化
package com.xxx.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account{
private long id;
private String username;
private String password;
private int age;
}
8.MyBatis动态SQL
使用动态SQL可简化代码的开发,减少开发这工作量,程序可以根据业务参数来决定SQL的组成
- if标签
<select id="findByAccount" parameterType="com.xxx.entity.Account" resultType="com.xxx.entity.Account">
select * from t_account where
<if test="id != 0">
id = #{id}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="age != 0">
and age = #{age}
</if>
</select>
if标签可以自动根据表达式的结果来决定是否将对应的语句加到Sql中,如果条件不成立,就不添加,否则就添加。
- where标签
<select id="findByAccount" parameterType="com.xxx.entity.Account" resultType="com.xxx.entity.Account">
select * from t_account
<where>
<if test="id != 0">
id = #{id}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="age != 0">
and age = #{age}
</if>
</where>
</select>
where标签可以自动判断是否要自动删除语句块中的and关键字,如果检测到where直接跟and拼接,则自动删除and,通常情况下if和where结合起来使用。
- choose、when标签
<select id="findByAccount" parameterType="com.xxx.entity.Account" resultType="com.xxx.entity.Account">
select * from t_account
<where>
<choose>
<when test="id != 0">
id = #{id}
</when>
<when test="password != null">
and password = #{password}
</when>
<when test="age != 0">
and age = #{age}
</when>
</choose>
</where>
</select>
- trim标签
trim标签中的prefix和suffix属性会被用于生成实际的SQL语句,回和标签内部的语句进行拼接,若果说语句前后出现了prefixOverrides或者suffixOverrides属性中指定的值,MyBatis框架会自动将其删除。
prefix和prefixOverrides的值一遇到就会删除。
<select id="findByAccount" parameterType="com.xxx.entity.Account" resultType="com.xxx.entity.Account">
select * from t_account
<trim prefix="where" prefixOverrides="and">
<choose>
<when test="id != 0">
id = #{id}
</when>
<when test="password != null">
and password = #{password}
</when>
<when test="age != 0">
and age = #{age}
</when>
</choose>
</trim>
</select>
- set标签
set标签用于update操作,会自动根据参数生成SQL语句。
<update id="update" parameterType="com.xxx.entity.Account">
update t_account
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="age != 0">
age=#{age}
</if>
</set>
where id=#{id}
</update>
- foreach标签
foreach标签可以迭代生成一系列的值,这个标签主要用于Sql的in语句。
<select id="findByIds" parameterType="com.xxx.entity.Account" resultType="com.xxx.entity.Account">
select * from t_account
<where>
-- collection:目标集合;open:集合之前 close:集合之后 item:变量名 separator:分割符号
<foreach collection="ids" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
and password = #{password}
</when>
<when test="age != 0">
and age = #{age}
</when>
</choose>
</trim>
</select>
* set标签
set标签用于update操作,会自动根据参数生成SQL语句。
~~~xml
<update id="update" parameterType="com.xxx.entity.Account">
update t_account
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="age != 0">
age=#{age}
</if>
</set>
where id=#{id}
</update>
- foreach标签
foreach标签可以迭代生成一系列的值,这个标签主要用于Sql的in语句。
<select id="findByIds" parameterType="com.xxx.entity.Account" resultType="com.xxx.entity.Account">
select * from t_account
<where>
-- collection:目标集合;open:集合之前 close:集合之后 item:变量名 separator:分割符号
<foreach collection="ids" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>