Mybatis 系列8-延迟加载
延迟加载
Mybatis的延迟加载
需要在SqlMapConfig.xml文件中添加配置:
<settings>
<!--开启Mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/><!--延迟记载总开关-->
<setting name="aggressiveLazyLoading" value="false" /><!--不启用延迟加载-->
</settings>
先创建个立即加载的项目,然后对比延迟加载和立即加载有什么不同
主配置文件SqlMapConfig.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-->
<properties resource="jdbcConfig.properties"></properties>
<!--配置参数 开启Mybatis支持延迟加载-->
<!--<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>-->
<!--使用typeAliases配置别名,它只能配置domain中类的别名 -->
<typeAliases>
<package name="com.mantishell.domain"></package>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!-- 配置mysql的环境-->
<environment id="mysql">
<!-- 配置事务 -->
<transactionManager type="JDBC"></transactionManager>
<!--配置连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<!-- 配置映射文件的位置 -->
<mappers>
<package name="com.mantishell.dao"></package>
</mappers>
</configuration>
jdbcConfig.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db2
jdbc.username=root
jdbc.password=123456
在resources下创建文件夹com/mantishell/dao
在dao文件夹下创建IAccountDao.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.mantishell.dao.IAccountDao">
<!-- 定义封装account和user的resultMap -->
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!-- 一对一的关系映射:配置封装user的内容
select属性指定的内容:查询用户的唯一标识,也就是填写调用select映射的id
column属性指定的内容:用户根据id查询时,所需要的参数的值,也就是填写传递给select映射的参数
-->
<association property="user" column="uid" javaType="user" select="com.mantishell.dao.IUserDao.findById"></association>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="accountUserMap">
select * from account
</select>
<!-- 根据用户id查询账户列表 -->
<select id="findAccountByUid" resultType="account">
select * from account where uid = #{uid}
</select>
</mapper>
创建实体类:
User.java
package com.mantishell.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
//一对多关系映射:主表实体应该包含从表实体的集合引用
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
Account.java
package com.mantishell.domain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//从表实体应该包含一个主表实体的对象引用
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
", user=" + user +
'}';
}
}
创建持久层接口:
package com.mantishell.dao;
import com.mantishell.domain.Account;
import java.util.List;
public interface IAccountDao {
/**
* 查询所有用户,同时获取到用户下所有账户的信息
* @return
*/
List<Account> findAll();
/**
* 根据用户id查询账户信息
* @param uid
* @return
*/
List<Account> findAccountByUid(Integer uid);
}
创建Account的测试
package com.mantishell.test;
import com.mantishell.dao.IAccountDao;
import com.mantishell.dao.IUserDao;
import com.mantishell.domain.Account;
import com.mantishell.domain.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class AccountTest {
private InputStream in;
private SqlSession sqlSession;
private IAccountDao accountDao;
@Before//用于在测试方法执行之前执行
public void init()throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
sqlSession = factory.openSession(true);
//4.获取dao的代理对象
accountDao = sqlSession.getMapper(IAccountDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy()throws Exception{
//提交事务
// sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
// for(Account account : accounts){
// System.out.println("-----每个用户的信息------");
// System.out.println(account);
// System.out.println(account.getUser());
// }
}
}
输出结果:
2020-03-17 21:51:20,416 189 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2020-03-17 21:51:20,668 441 [ main] DEBUG source.pooled.PooledDataSource - Created connection 22805895.
2020-03-17 21:51:20,675 448 [ main] DEBUG ishell.dao.IAccountDao.findAll - ==> Preparing: select * from account
2020-03-17 21:51:20,725 498 [ main] DEBUG ishell.dao.IAccountDao.findAll - ==> Parameters:
2020-03-17 21:51:20,751 524 [ main] DEBUG ntishell.dao.IUserDao.findById - ====> Preparing: select * from user where id = ?
2020-03-17 21:51:20,751 524 [ main] DEBUG ntishell.dao.IUserDao.findById - ====> Parameters: 46(Integer)
2020-03-17 21:51:20,758 531 [ main] DEBUG ntishell.dao.IUserDao.findById - <==== Total: 1
2020-03-17 21:51:20,758 531 [ main] DEBUG ntishell.dao.IUserDao.findById - ====> Preparing: select * from user where id = ?
2020-03-17 21:51:20,758 531 [ main] DEBUG ntishell.dao.IUserDao.findById - ====> Parameters: 45(Integer)
2020-03-17 21:51:20,764 537 [ main] DEBUG ntishell.dao.IUserDao.findById - <==== Total: 1
2020-03-17 21:51:20,765 538 [ main] DEBUG ishell.dao.IAccountDao.findAll - <== Total: 3
2020-03-17 21:51:20,765 538 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@15bfd87]
2020-03-17 21:51:20,767 540 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 22805895 to pool.
重点来了:在SqlMapConfig.xml中添加
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
再次运行
2020-03-17 21:52:43,728 156 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2020-03-17 21:52:43,982 410 [ main] DEBUG source.pooled.PooledDataSource - Created connection 40472007.
2020-03-17 21:52:43,992 420 [ main] DEBUG ishell.dao.IAccountDao.findAll - ==> Preparing: select * from account
2020-03-17 21:52:44,049 477 [ main] DEBUG ishell.dao.IAccountDao.findAll - ==> Parameters:
2020-03-17 21:52:44,120 548 [ main] DEBUG ishell.dao.IAccountDao.findAll - <== Total: 3
2020-03-17 21:52:44,121 549 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2698dc7]
2020-03-17 21:52:44,121 549 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 40472007 to pool.
放一张对比图:
最后放上IUserDao、IUserDao.xml
package com.mantishell.dao;
import com.mantishell.domain.User;
import java.util.List;
public interface IUserDao {
/**
* 查询所有用户,同时获取到用户下所有账户的信息
* @return
*/
List<User> findAll();
/**
* 根据id查询用户信息
* @param userId
* @return
*/
User findById(Integer userId);
}
<?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.mantishell.dao.IUserDao">
<!-- 定义User的resultMap-->
<resultMap id="userMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="address" column="address"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<!-- 配置user对象中accounts集合的映射 -->
<collection property="accounts" ofType="account" fetchType="lazy" select="com.mantishell.dao.IAccountDao.findAccountByUid" column="id"/><!--这里的id是user表的id-->
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="userMap">
select * from user
</select>
<!-- 根据id查询用户 -->
<select id="findById" parameterType="INT" resultType="user">
select * from user where id = #{uid}
</select>
</mapper>