mybatis延迟加载一对一和一对多
程序员文章站
2022-07-12 22:30:08
...
Mybatis (一对一 和 一对多) 延迟加载
(重点是SqlMapConfig.xml中的settings)
(重点是accountDao.xml中的association写法)
(重点是userDao.xml中的collection写法)
(其他跟立即加载的没什么区别)
项目结构
什么时候使用延迟
问题: 在一对多中, 当我们有一个用户, 他有100个账户.
在查询用户的时候, 要不要把关联的账户查出来?
在查询账户的时候, 要不要把关联的用户查出来?
在查询用户时, 用户下的账户信息应该是, 什么时候使用, 什么时候查询的.
在查询账户时, 账户的所属用户信息应该是随着账户查询时一起查询出来.
什么是延迟加载
在真正使用数据时才发起查询, 不用的时候不查询. 按需加载(懒加载)
什么是立即加载
不管用不用, 只要一调用方法, 马上发起查询.
在对应的四种表关系中: 一对多, 多对一, 一对一, 多对多
一对多, 多对多: 通常情况下都是采用延迟加载.
多对一, 一对一: 通常情况下都是采用立即加载.
配置文件
-
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.xiaoge</groupId> <artifactId>azy</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</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> </project>
-
jdbcConfig.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/eesy_mybatis jdbc.username=root jdbc.password=123456
-
SqlMapConfig.xml(重点setting这是开启延迟加载)
<?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> <!-- 配置参数 --> <settings> <!-- 开启Mybatis支持延迟加载 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings> <!-- 使用typeAliases配置别名, 它只能配置domain中类的别名 --> <typeAliases> <package name="com.xiaoge.domain"></package> </typeAliases> <!--配置环境--> <environments default="mysql"> <!--配置mysql环境--> <environment id="mysql"> <!--配置事务--> <transactionManager type="JDBC"></transactionManager> <!--配置连接池--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <package name="com.xiaoge.dao"></package> </mappers> </configuration>
-
accountDao.xml(一对一: 重点association这里用了延迟加载, 通常的association那种写法是立即加载. 列: 立即加载: 是没有settings和association的常规写法)
<?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.xiaoge.dao.AccountDao"> <!-- 定义封装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的内容 javaType是下面谢谢信息, 封装在哪个实体类中 select属性指定的内容: 查询用户的唯一标识: (用户id是唯一的, 而userDao里面只有com.xiaoge.dao.UserDao.findById方法是根据用户id查询用户的) column属性指定的内容: 用户根据id查询时, 所需要的参数的值 (用户id对应的是account里的uid, 所以column, 在使用延迟加载时必须写) (简单的说column给定的字段值, 被用户作为id值查询了用户) --> <association property="user" column="uid" javaType="user" select="com.xiaoge.dao.UserDao.findById"> </association> </resultMap> <!-- 查询所有 --> <select id="findAll" resultMap="accountUserMap"> select * from account </select> <!-- 根据用户id查询所有账户 --> <select id="findAccountByUid" resultType="account" parameterType="java.lang.Integer"> select * from account where uid = #{uid} </select> </mapper>
-
userDao.xml(一对多: 重点collection这里用了延迟加载, 通常的collection那种写法是立即加载. 列: 立即加载: 是没有settings和collection的常规写法)
<?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.xiaoge.dao.UserDao"> <resultMap id="userAccountMap" type="user"> <id property="id" column="id"></id> <result property="username" column="username"></result> <result property="birthday" column="birthday"></result> <result property="sex" column="sex"></result> <result property="address" column="address"></result> <!-- 配置user对象中accounts集合的映射 ofType是指定accounts集合中元素的类型 我这里写Account是因为我去了别名的 select属性指定的内容: 查询账户的唯一标识: (用户id是唯一的, 而accountDao里面只有com.xiaoge.dao.AccountDao.findAccountByUid方法是根据账户uid查询账户的) column属性指定的内容: 账户根据uid查询时, 所需要的参数的值 (账户uid对应的是user里的id, 所以column, 在使用延迟加载时必须写) (简单的说column给定的字段值, 被用户作为id值查询了用户) --> <collection property="accounts" ofType="Account" column="id" select="com.xiaoge.dao.AccountDao.findAccountByUid"> </collection> </resultMap> <!-- 查询所有用户操作 --> <select id="findAll" resultMap="userAccountMap"> select * from user </select> <!--查询条记录信息--> <select id="findById" parameterType="java.lang.Integer" resultType="user"> select * from user where id = #{userId} </select> </mapper>
实体类
-
User
package com.xiaoge.domain; import java.util.Date; import java.util.List; /** * @Author: 潇哥 * @DateTime: 2020/3/4 下午4:03 * @Description: TODO */ public class User { 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
package com.xiaoge.domain; /** * @Author: 潇哥 * @DateTime: 2020/3/16 下午6:02 * @Description: TODO */ public class Account { 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 + '}'; } }
持久层接口
-
UserDao
package com.xiaoge.dao; import com.xiaoge.domain.User; import java.util.List; /** * @Author: 潇哥 * @DateTime: 2020/3/4 下午4:19 * @Description: 用户的持久层接口 */ public interface UserDao { /** * 查询所有用户, 同时获取到用户下所有账户的信息 * @return */ public List<User> findAll(); }
-
AccountDao
package com.xiaoge.dao; import com.xiaoge.domain.Account; import java.util.List; /** * @Author: 潇哥 * @DateTime: 2020/3/16 下午6:08 * @Description: TODO */ public interface AccountDao { /** * 查询所有账户, 同时还要获取当前账户的所属用户信息 * @return */ public List<Account> findAll(); /** * 根据用户id查询账户信息 * @param uid * @return */ public List<Account> findAccountByUid(Integer uid); }
测试持久层接口方法
-
UserTest
package com.xiaoge.test; import com.xiaoge.dao.UserDao; import com.xiaoge.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.IOException; import java.io.InputStream; import java.util.List; /** * @Author: 潇哥 * @DateTime: 2020/3/16 下午6:12 * @Description: TODO */ public class UserTest { private SqlSession session; private UserDao userDao; private InputStream is; @Before public void init() throws IOException { is = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(is); session = factory.openSession(); userDao = session.getMapper(UserDao.class); } @After public void destroy() throws IOException { if (session != null) { session.commit(); session.close(); } if (is != null) { is.close(); } } /** * 测试查询所有 */ @Test public void findAllTest(){ List<User> list = userDao.findAll(); for (User user : list) { System.out.println("-----------每个user信息------------"); System.out.println(user); System.out.println(user.getAccounts());// 这里使用到了for遍历把每一个user显示出来, 所以这里回去拿账户信息, 所以会查询, 当不遍历时, 是不会去拿账户信息的 } // 运行结果 (有: for遍历时) 2020-03-18 13:10:05,072 1439 [ main] DEBUG com.xiaoge.dao.UserDao.findAll - ==> Preparing: select * from user // 这里 2020-03-18 13:10:05,171 1538 [ main] DEBUG com.xiaoge.dao.UserDao.findAll - ==> Parameters: 2020-03-18 13:10:05,238 1605 [ main] DEBUG com.xiaoge.dao.UserDao.findAll - <== Total: 11 -----------每个user信息------------ 2020-03-18 13:10:05,242 1609 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,242 1609 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 41(Integer) 2020-03-18 13:10:05,245 1612 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 1 User{id=41, username='老王', address='北京', sex='男', birthday=Wed Feb 28 07:47:08 CST 2018} [Account{id=1, uid=41, money=1000.0}] -----------每个user信息------------ 2020-03-18 13:10:05,248 1615 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,248 1615 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 42(Integer) 2020-03-18 13:10:05,250 1617 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 1 User{id=42, username='小二王', address='北京金燕龙', sex='女', birthday=Sat Mar 03 05:09:37 CST 2018} [Account{id=2, uid=42, money=1000.0}] -----------每个user信息------------ 2020-03-18 13:10:05,250 1617 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,250 1617 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 43(Integer) 2020-03-18 13:10:05,252 1619 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 2 User{id=43, username='小二王', address='北京金燕龙', sex='女', birthday=Mon Mar 05 01:34:34 CST 2018} [Account{id=3, uid=43, money=2000.0}, Account{id=4, uid=43, money=3000.0}] -----------每个user信息------------ 2020-03-18 13:10:05,253 1620 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,253 1620 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 46(Integer) 2020-03-18 13:10:05,254 1621 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=46, username='老王', address='北京', sex='女', birthday=Thu Mar 08 07:37:26 CST 2018} [] -----------每个user信息------------ 2020-03-18 13:10:05,255 1622 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,255 1622 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 48(Integer) 2020-03-18 13:10:05,256 1623 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=48, username='小马宝莉', address='北京修正', sex='女', birthday=Fri Mar 09 01:44:00 CST 2018} [] -----------每个user信息------------ 2020-03-18 13:10:05,256 1623 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,257 1624 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 53(Integer) 2020-03-18 13:10:05,258 1625 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=53, username='啸哥', address='北京四合院', sex='男', birthday=Fri Mar 06 13:10:42 CST 2020} [] -----------每个user信息------------ 2020-03-18 13:10:05,259 1626 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,259 1626 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 54(Integer) 2020-03-18 13:10:05,260 1627 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=54, username='李四 last insertid', address='北京', sex='男', birthday=Fri Mar 06 14:26:40 CST 2020} [] -----------每个user信息------------ 2020-03-18 13:10:05,261 1628 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,262 1629 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 55(Integer) 2020-03-18 13:10:05,263 1630 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=55, username='王五 last insertid', address='北京', sex='男', birthday=Fri Mar 06 15:17:43 CST 2020} [] -----------每个user信息------------ 2020-03-18 13:10:05,263 1630 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,264 1631 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 56(Integer) 2020-03-18 13:10:05,265 1632 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=56, username='李六 last insertid', address='北京', sex='男', birthday=Fri Mar 06 18:47:48 CST 2020} [] -----------每个user信息------------ 2020-03-18 13:10:05,265 1632 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,265 1632 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 57(Integer) 2020-03-18 13:10:05,266 1633 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=57, username='李六 last insertid', address='北京', sex='男', birthday=Fri Mar 06 19:11:40 CST 2020} [] -----------每个user信息------------ 2020-03-18 13:10:05,267 1634 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ? // 这里 2020-03-18 13:10:05,267 1634 [ main] DEBUG ao.AccountDao.findAccountByUid - ==> Parameters: 59(Integer) 2020-03-18 13:10:05,268 1635 [ main] DEBUG ao.AccountDao.findAccountByUid - <== Total: 0 User{id=59, username='李白 last insertid', address='北京', sex='男', birthday=Wed Mar 11 18:17:20 CST 2020} [] // 运行结果 (没有: for遍历时) 2020-03-18 13:12:09,482 1463 [ main] DEBUG com.xiaoge.dao.UserDao.findAll - ==> Preparing: select * from user // 这里 2020-03-18 13:12:09,534 1515 [ main] DEBUG com.xiaoge.dao.UserDao.findAll - ==> Parameters: 2020-03-18 13:12:09,611 1592 [ main] DEBUG com.xiaoge.dao.UserDao.findAll - <== Total: 11 } }
-
AccountTest
package com.xiaoge.test; import com.xiaoge.dao.AccountDao; import com.xiaoge.domain.Account; 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.IOException; import java.io.InputStream; import java.util.List; /** * @Author: 潇哥 * @DateTime: 2020/3/16 下午6:12 * @Description: TODO */ public class AccountTest { private SqlSession session; private AccountDao accountDao; private InputStream is; @Before public void init() throws IOException { is = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(is); session = factory.openSession(); accountDao = session.getMapper(AccountDao.class); } @After public void destroy() throws IOException { if (session != null) { session.commit(); session.close(); } if (is != null) { is.close(); } } /** * 测试查询所有 */ @Test public void findAllTest(){ List<Account> list = accountDao.findAll(); for (Account account : list) { System.out.println("-----------每个account信息------------"); System.out.println(account); System.out.println(account.getUser()); // 这里使用到了for遍历把每一个account显示出来, 所以这里回去拿用户信息, 所以会查询, 当不遍历时, 是不会去拿用户信息的 } // 运行结果 (有: for遍历时) 2020-03-18 12:28:45,303 1882 [ main] DEBUG .xiaoge.dao.AccountDao.findAll - ==> Preparing: select * from account // 这里 2020-03-18 12:28:45,361 1940 [ main] DEBUG .xiaoge.dao.AccountDao.findAll - ==> Parameters: 2020-03-18 12:28:45,486 2065 [ main] DEBUG .xiaoge.dao.AccountDao.findAll - <== Total: 4 -----------每个account信息------------ 2020-03-18 12:28:45,489 2068 [ main] DEBUG om.xiaoge.dao.UserDao.findById - ==> Preparing: select * from user where id = ? // 这里 2020-03-18 12:28:45,490 2069 [ main] DEBUG om.xiaoge.dao.UserDao.findById - ==> Parameters: 41(Integer) 2020-03-18 12:28:45,493 2072 [ main] DEBUG om.xiaoge.dao.UserDao.findById - <== Total: 1 Account{id=1, uid=41, money=1000.0} User{id=41, username='老王', address='北京', sex='男', birthday=Wed Feb 28 07:47:08 CST 2018} -----------每个account信息------------ 2020-03-18 12:28:45,496 2075 [ main] DEBUG om.xiaoge.dao.UserDao.findById - ==> Preparing: select * from user where id = ? // 这里 2020-03-18 12:28:45,497 2076 [ main] DEBUG om.xiaoge.dao.UserDao.findById - ==> Parameters: 42(Integer) 2020-03-18 12:28:45,498 2077 [ main] DEBUG om.xiaoge.dao.UserDao.findById - <== Total: 1 Account{id=2, uid=42, money=1000.0} User{id=42, username='小二王', address='北京金燕龙', sex='女', birthday=Sat Mar 03 05:09:37 CST 2018} -----------每个account信息------------ 2020-03-18 12:28:45,499 2078 [ main] DEBUG om.xiaoge.dao.UserDao.findById - ==> Preparing: select * from user where id = ? // 这里 2020-03-18 12:28:45,499 2078 [ main] DEBUG om.xiaoge.dao.UserDao.findById - ==> Parameters: 43(Integer) 2020-03-18 12:28:45,501 2080 [ main] DEBUG om.xiaoge.dao.UserDao.findById - <== Total: 1 Account{id=3, uid=43, money=2000.0} User{id=43, username='小二王', address='北京金燕龙', sex='女', birthday=Mon Mar 05 01:34:34 CST 2018} -----------每个account信息------------ Account{id=4, uid=43, money=3000.0} User{id=43, username='小二王', address='北京金燕龙', sex='女', birthday=Mon Mar 05 01:34:34 CST 2018} // 运行结果 (没有: for遍历时) 2020-03-18 12:33:16,949 1480 [ main] DEBUG .xiaoge.dao.AccountDao.findAll - ==> Preparing: select * from account // 这里, 只查询了account 2020-03-18 12:33:17,008 1539 [ main] DEBUG .xiaoge.dao.AccountDao.findAll - ==> Parameters: 2020-03-18 12:33:17,083 1614 [ main] DEBUG .xiaoge.dao.AccountDao.findAll - <== Total: 4 } }
上一篇: Mybatis实现一对多查询
推荐阅读
-
MyBatis从入门到精通(十一):MyBatis高级结果映射之一对多映射
-
Mybatis使用注解实现一对一复杂关系映射及延迟加载
-
【MyBatis】多对一与一对多处理
-
MyBatis一对多嵌套查询的完整实例
-
Mybatis一对多与多对一查询处理详解
-
Mybatis学习笔记------mybatis的多表查询-一对多
-
Mybatis使用注解实现一对一复杂关系映射及延迟加载
-
Mybatis04—注解开发实现CRUD以及实现一对一、一对多及多对多复杂关系映射
-
Mybatis常用的注解开发CRUD&&复杂关系映射(一对一,一对多)&&mybatis 基于注解的二级缓存
-
Mybatis—— 使用注解实现一对一复杂关系映射及延迟加载