概述
- 原名iBatis
- 实现数据持久化,对JDBC进行封装
- ORM(Object-Relationship Mapping)对象关系映射
- 对象:OOP
- 关系:关系型数据库SQL
- eg.Java到MySQL的映射,开发者用OOP思想管理数据库
优点
- 比JDBC代码量减少一半
- 小巧灵活,SQL写在XML里,从程序代码中分离解耦
- 提供XML标签,支持编写动态SQL语句
- 提供映射标签,支持对象与数据库的ORM字段关系映射
缺点
- SQL语句编写工作量大
- SQL语句依赖数据库,移植性差
核心接口/类
- SqlSessionFactoryBuilder
- build()
- SqlSessionFactory
- openSession()
- SqlSession
开发方式
- 使用原生接口
- Mapper代理实现自定义接口
使用
- 新建普通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>com.microsoft</groupId>
<artifactId>aimybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
- 新建数据表
use mybatis
create table t_account(
id int primary key auto_increment,
username varchar(11),
password varchar(11),
age int
)
- 新建对应实体类Account
package com.microsoft.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运行环境 -->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- POOLED配置JDBC数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="admin"></property>
</dataSource>
</environment>
</environments>
</configuration>
- 方法一:使用原生接口【麻烦,不推荐】
开发者自定义SQL语句,写在AccountMapper.xml文件中,一个实体类对应一个管理它的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.microsoft.mapper.AccountMapper">
<insert id="save" parameterType="com.microsoft.entity.Account">
insert into t_account(username, password, age) values(#{username},#{password},#{age})
</insert>
</mapper>
-
namespace 通常设置为文件所在包+文件名的形式(全限定类名)
-
id 是实际调用MyBatis方法时要用到的参数
-
parameterType 是调用对应方法时参数的数据类型
-
在全局配置文件config.xml中注册AccountMapper.xml
<!--注册Mapper.xml-->
<mappers>
<mapper resource="com/microsoft/mapper/AccountMapper.xml"></mapper>
</mappers>
- 调用MyBatis原生接口执行添加操作
package com.microsoft.test;
import com.microsoft.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) {
//加载配置文件
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
String statement = "com.microsoft.mapper.AccountMapper.save";
Account account = new Account(1L,"张三","123123",18);
sqlSession.insert(statement,account);
sqlSession.commit();
sqlSession.close();
}
}
- 如果报错,可能因为插入中文,创建表的时候要记得啊
alter table mybatis.t_account change username username varchar(11) character set utf8;
- 方法二:Mapper代理实现自定义接口【推荐】
MyBatis动态生成实现类,不用我们操心
步骤:
- 自定义接口,定义相关业务方法
- 编写方法与方法相对应的Mapper.xml
1、自定义接口
package com.microsoft.repository;
import com.microsoft.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();
public Account findBYId(long id);
}
2、创建接口对应的Mapper.xml,定义接口方法对应的SQL语句
statement 标签会根据SQL执行的业务选择 insert、delete、update、select
规则:
- Mapper.xml中namespace为接口的全类名
- Mapper.xml中statement的id接口中对应的方法名
- Mapper.xml中statement的parameterType和接口中对应方法的参数类型一致
- Mapper.xml中statement的resultType和接口中对应的返回值类型一致(大部分已经默认了int)
AccountMapper.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.microsoft.repository.AccountRepository">
<insert id="save" parameterType="com.microsoft.entity.Account">
insert into t_account(username, password, age) values(#{username},#{password},#{age})
</insert>
<update id="update" parameterType="com.microsoft.entity.Account">
update t_account set username = #{usename},password = #{password},age = #{age} where id = #{id}
</update>
<delete id="deleteById" parameterType="java.lang.Long">
delete from t_account where id = #{id}
</delete>
<!--写泛型-->
<select id="findAll" resultType="com.microsoft.entity.Account">
select * from t_account
</select>
<select id="findById" parameterType="long" resultType="com.microsoft.entity.Account">
select * from t_account where id = #{id}
</select>
</mapper>
3、在config.xml中注册AccountMapper.xml
<mapper resource="com/microsoft/repository/AccountMapper.xml"></mapper>
4、调用接口的代理对象完成相关的业务操作【CRUD】
package com.microsoft.test;
import com.microsoft.entity.Account;
import com.microsoft.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) {
InputStream inputStream = Test.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 = new Account(2L,"李四","123456",19);
accountRepository.save(account);
// 增删改(数据改变)的操作一定要提交事务,才能持久化数据
sqlSession.commit();*/
//查询所有对象
List<Account> list = accountRepository.findAll();
for(Account account1 : list){
System.out.println(account1);
}
/* 查询单个对象
Account result = null;
result = accountRepository.findById(3L);
System.out.println(result); */
/* 删除对象
accountRepository.deleteById(3L);
List<Account> list = accountRepository.findAll();
for(Account account1 : list){
System.out.println(account1);
}
sqlSession.commit(); */
sqlSession.close();
}
}
- 多个参数传入(把
param
替换成arg
也行,但是要改成arg0,arg1)
<select id="findByNameAndAge" resultType="com.microsoft.entity.Account">
select * from t_account where username = #{param1} and age = #{param2}
</select>
- 计数
<select id="count" resultType="int">
select count(id) from t_account
</select>
级联查询
一对多
- 建表
use mybatis;
create table student(
id int NOT NULL AUTO_INCREMENT,
name varchar(30) DEFAULT NULL,
cid int ,
PRIMARY KEY (id)
)AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
use mybatis;
create table classes(
id int NOT NULL AUTO_INCREMENT,
name varchar(30) DEFAULT NULL,
PRIMARY KEY (id)
)AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
- 设置外键
use mybatis;
alter table student add constraint cid foreign key(cid) references classes(id)
- 注册mapper
<mapper resource="com/microsoft/repository/StudentRepository.xml"></mapper>
- 创建Student实体类
package com.microsoft.entity;
import lombok.Data;
@Data
public class Student {
private long id;
private String name;
private Classes classes;
}
- 创建Classes实体类
package com.microsoft.entity;
import lombok.Data;
import java.util.List;
@Data
public class Classes {
private long id;
private String name;
private List<Student> students;
}
- 创建StudentRepository接口
package com.microsoft.repository;
import com.microsoft.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.microsoft.repository.StudentRepository">
<resultMap id="studentMap" type="com.microsoft.entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="com.microsoft.entity.Classes">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
</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>
反向查
- 创建ClassesRepository接口
package com.microsoft.repository;
import com.microsoft.entity.Classes;
public interface ClassesRepository {
public Classes findById(long id);
}
- 配置ClassesRepository.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.microsoft.repository.ClassesRepository">
<resultMap id="classesMap" type="com.microsoft.entity.Classes">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
<collection property="students" ofType="com.microsoft.entity.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
</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>
多对多
-
本质:两个一对多
-
准备三张表
- customer(id,name)
- goods(id,name)
- customer_goods(id,cuid,gid)cuid,gid是外键,分别对应前两者
-
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.microsoft.repository.CustomerRepository">
<resultMap id="customerMap" type="com.microsoft.entity.Customer">
<id column="cuid" property="id"></id>
<result column="cuname" property="name"></result>
<collection property="goods" ofType="com.microsoft.entity.Goods">
<id column="gid" property="id"/>
<result column="gname" property="name"/>
</collection>
</resultMap>
<select id="findById" parameterType="long" resultMap="customerMap">
select c.id cuid,c.name cuname,g.id gid,g.name gname from customer c,goods g,customer_goods cg where c.id=#{id} and cg.cuid=c.id and cg.gid=g.id
</select>
</mapper>
- GoodsRepository.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.microsoft.repository.GoodsRepository">
<resultMap id="goodsMap" type="com.microsoft.entity.Goods">
<id column="gid" property="id"></id>
<result column="gname" property="name"></result>
<collection property="customers" ofType="com.microsoft.entity.Customer">
<id column="cuid" property="id"/>
<result column="cuname" property="name"/>
</collection>
</resultMap>
<select id="findById" parameterType="long" resultMap="goodsMap">
select c.id cuid,c.name cuname,g.id gid,g.name gname from customer c,goods g,customer_goods cg where g.id=#{id} and cg.cuid=c.id and cg.gid=g.id
</select>
</mapper>
逆向工程
MyBatis需要:实体类,自定义Mapper接口、Mapper.xml
传统开发:上述三个组件需要开发者手动创建
逆向工程:帮助开发者自动创建
缺点:根据数据表重复生成,需要我们自己控制资源
使用
MyBatis Generator(MGB)——代码生成器,支持基本CRUD,复杂的干不了嗷
- 添加依赖
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
- 创建MBG配置文件 generatorConfig.xml
1、JDBCConnection 配置连接信息
2、JavaModelGenerator 配置JavaBean的生成策略
3、sqlMapGenerator 配置SQL映射文件生成策略
4、JavaClientGenerator 配置Mapper接口的生成策略
5、table 配置目标数据表(tableName:表名,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>
<context id="testTables" targetRuntime="MyBatis3">
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8"
userId="root"
password="admin"
></jdbcConnection>
<javaModelGenerator targetPackage="com.microsoft.entity" targetProject="./src/main/java"></javaModelGenerator>
<sqlMapGenerator targetPackage="com.microsoft.repository" targetProject="./src/main/java"></sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.microsoft.repository" targetProject="./src/main/java"></javaClientGenerator>
<table tableName="t_user" domainObjectName="User"></table>
</context>
</generatorConfiguration>
- 启动类的编写
package com.microsoft.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 Test4 {
public static void main(String[] args) {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
String genCig = "/generatorConfig.xml";
File configFile = new File(Test4.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();
}
}
}
这时候就自己生成啦!!!有User,也有UserExample(辅助:去重…),还有Mapper接口及xml
延迟加载
- 本质:动态决定查几张表
- AKA:懒加载、惰性加载
- 作用:提高程序运行效率
- 针对于数据持久层的操作,在某些特定的情况下去访问特定的数据,其他情况下可以不访问某些表,从一定程度上减少了Java应用与数据库的交互次数
查询学生和班级的时候(是2张不同的表),如果当前需求只需要获取学生信息,那么查询学生单表即可,要班级信息再查两张表。不同需求,不同操作。
- config.xml里配置日志
<settings>
<!--打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
- StudentRepository.xml配置(多表关联拆分)
<resultMap id="studentMapLazy" type="com.microsoft.entity.Student">
<id column="id" property="id"></id>
<result column="name" property="name"></result>
<association property="classes" javaType="com.microsoft.entity.Classes"
select="com.microsoft.repository.ClassesRepository.findByIdLazy"
column="cid">
</association>
</resultMap>
<select id="findByIdLazy" parameterType="long" resultMap="studentMapLazy">
select * from student where id=#{id}
</select>
- ClassesRepository.xml配置
<select id="findByIdLazy" parameterType="long" resultType="com.microsoft.entity.Classes">
select * from classes where id = #{id}
</select>
- 测试
InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
StudentRepository studentRepository = sqlSession.getMapper(StudentRepository.class);
Student student = studentRepository.findByIdLazy(1L);
System.out.println(student.getName());
- 控制台输出(查两次)
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 2092769598.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
==> Preparing: select * from student where id=?
==> Parameters: 1(Long)
<== Columns: id, name, cid
<== Row: 1, 张三, 2
====> Preparing: select * from classes where id = ?
====> Parameters: 2(Long)
<==== Columns: id, name
<==== Row: 2, 6班
<==== Total: 1
<== Total: 1
Student(id=1, name=张三, classes=Classes(id=2, name=6班, students=null))
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
Returned connection 2092769598 to pool.
但这时候还没开启延迟加载,我们去get学生的name,还是会查两次
- 配置config.xml
<settings>
<!--打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
</settings>
- 控制台输出(查一次)
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 2092769598.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
==> Preparing: select * from student where id=?
==> Parameters: 1(Long)
<== Columns: id, name, cid
<== Row: 1, 张三, 2
<== Total: 1
张三
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
Returned connection 2092769598 to pool.
缓存
- 作用:减少java应用和数据库的交互次数,从而提升程序运行效率(和延迟加载作用类似)
- 比如查询id=1的对象,第一次查询出之后会自动将该对象保存再缓存中,当下一次查询时,直接从缓存里面拿就好,就不访问数据库了
分类
一级缓存SqlSession级别,默认开启,且不能关闭
- 操作数据库时需要创建SqlSession对象,在对象里有个HashMap用于存储缓存数据,不同的SqlSession之间缓存数据区域互不影响
- 需要注意的是,如果SqlSession执行了DML(增删改,数据变动),缓存必须清空,保证数据准确性
测试1
package com.microsoft.test;
import com.microsoft.entity.Account;
import com.microsoft.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 Test5 {
public static void main(String[] args) {
InputStream inputStream = Test5.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(1L);
System.out.println(account);
Account account1 = accountRepository.findById(1L);
System.out.println(account1);
}
}
运行结果1
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 2092769598.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
==> Preparing: select * from t_account where id = ?
==> Parameters: 1(Long)
<== Columns: id, username, password, age
<== Row: 1, 张三, 123123, 18
<== Total: 1
Account(id=1, username=张三, password=123123, age=18)
Account(id=1, username=张三, password=123123, age=18)
代码2
package com.microsoft.test;
import com.microsoft.entity.Account;
import com.microsoft.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 Test5 {
public static void main(String[] args) {
InputStream inputStream = Test5.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(1L);
System.out.println(account);
sqlSession.close();
sqlSession = sqlSessionFactory.openSession();
accountRepository = sqlSession.getMapper(AccountRepository.class);
Account account1 = accountRepository.findById(1L);
System.out.println(account1);
}
}
结果2
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 2092769598.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
==> Preparing: select * from t_account where id = ?
==> Parameters: 1(Long)
<== Columns: id, username, password, age
<== Row: 1, 张三, 123123, 18
<== Total: 1
Account(id=1, username=张三, password=123123, age=18)
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
Returned connection 2092769598 to pool.
Opening JDBC Connection
Checked out connection 2092769598 from pool.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7cbd213e]
==> Preparing: select * from t_account where id = ?
==> Parameters: 1(Long)
<== Columns: id, username, password, age
<== Row: 1, 张三, 123123, 18
<== Total: 1
Account(id=1, username=张三, password=123123, age=18)
二级缓存:Mapper级别,默认关闭,可以开启
- 多个SqlSession使用同一个Mapper的SQL语句操作数据库,得到的数据会在二级缓存区
- 同样是用HashMap进行数据存储,相比较于一级缓存,二级缓存范围更大,多个SqlSession可以共用二级缓存
- 跨SqlSession
- 多个SqlSession共享,其作用域是Mapper的同一个namespace
1、MyBatis自带的
- config.xml配置
<settings>
<!--打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
- Mapper.xml中配置(mapper中添加)
<cache></cache>
- 实体类实现序列化接口
package com.microsoft.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;
}
- 运行结果
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Cache Hit Ratio [com.microsoft.repository.AccountRepository]: 0.0
Opening JDBC Connection
Created connection 1372082959.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@51c8530f]
==> Preparing: select * from t_account where id = ?
==> Parameters: 1(Long)
<== Columns: id, username, password, age
<== Row: 1, 张三, 123123, 18
<== Total: 1
Account(id=1, username=张三, password=123123, age=18)
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@51c8530f]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@51c8530f]
Returned connection 1372082959 to pool.
Cache Hit Ratio [com.microsoft.repository.AccountRepository]: 0.5
Account(id=1, username=张三, password=123123, age=18)
2、ehcache 二级缓存(第三方)
- 添加依赖
<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在resource下
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore/>
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
- config.xml中配置
<settings>
<!--打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
- Mapper.xml中配置(mapper中添加)
<cache type="org.mybatis.caches.ehcache.EhcacheCache">
<!-- 缓存创建之后,最后一次访问缓存的时间至缓存失效的时间间隔 -->
<property name="timeToIdleSeconds" value="3600"/>
<!-- 缓存自创建时间起至失效的时间间隔 -->
<property name="timeToLiveSeconds" value="3600"/>
<!-- 缓存回收策略,LRU表示移除近期使用最少的对象 -->
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>
-
实体类不需要实现序列化接口
-
运行结果(效果类似)
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Cache Hit Ratio [com.microsoft.repository.AccountRepository]: 0.0
Opening JDBC Connection
Created connection 146370526.
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8b96fde]
==> Preparing: select * from t_account where id = ?
==> Parameters: 1(Long)
<== Columns: id, username, password, age
<== Row: 1, 张三, 123123, 18
<== Total: 1
Account(id=1, username=张三, password=123123, age=18)
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8b96fde]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@8b96fde]
Returned connection 146370526 to pool.
Cache Hit Ratio [com.microsoft.repository.AccountRepository]: 0.5
Account(id=1, username=张三, password=123123, age=18)
动态SQL
简化代码的开发,减少开发者的工作量,自动根据业务组成来创建SQL
- if/where标签
<select id="findByAccount" parameterType="com.microsoft.entity.Account" resultType="com.microsoft.entity.Account">
select * from t_account
<where>
<if test="id != 0">
id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="age != 0">
and age = #{age}
</if>
</where>
</select>
if标签可以自动根据表达式的结果来决定是否将对应的语句添加到SQL中,若不成立,则不添加
where标签可以自动判断是否删除语句块中的and,如果检测到where和and连接,会自动去除
- choose/when标签
<select id="findByAccount" parameterType="com.microsoft.entity.Account" resultType="com.microsoft.entity.Account">
select * from t_account
<where>
<choose>
<when test="id != 0">
id = #{id}
</when>
<when test="username != null">
username = #{username}
</when>
<when test="password != null">
password = #{password}
</when>
<when test="age != 0">
age = #{age}
</when>
</choose>
</where>
</select>
第一个when成立,不会去找下面的了
- trim标签
trim标签中的 prefix 和 suffix 属性会被用于生成实际的SQL语句,会和标签内部的语句进行拼接,如果语句前后出现了prefixOverrides 或者 suffixOverrides 属性中指定的值,框架会自动将其删除
<select id="findByAccount" parameterType="com.microsoft.entity.Account" resultType="com.microsoft.entity.Account">
select * from t_account
<trim prefix="where" prefixOverrides="and">
<if test="id != 0">
id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="age != 0">
and age = #{age}
</if>
</trim>
</select>
- set标签
set标签用于update操作,会自动根据参数,选择SQL语句
<update id="update" parameterType="com.microsoft.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.microsoft.entity.Account" resultType="com.microsoft.entity.Account">
select * from t_account
<where>
<foreach collection="ids" open="id in (" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>