mybatis延迟加载举例
文章目录
开启延迟加载
#延迟加载总开关
mybatis-plus.configuration.lazy-loading-enabled=true
#设置按需加载
mybatis-plus.configuration.aggressive-lazy-loading=false表关系
Mapper文件配置
IAccountDao.xml mapper配置文件
<mapper namespace="com.itheima.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属性指定的内容:查询用户的唯一标识:
column属性指定的内容:用户根据id查询时,所需要的参数的值(resultMap中id项的column)
property为account实体类中有关association的实体类的名称
javaType表示association中实体类的类型
-->
<association property="user" column="uid" javaType="user" select="com.itheima.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>IUserDao.xml mapper配置
<mapper namespace="com.itheima.dao.IUserDao">
<!-- 定义User的resultMap-->
<resultMap id="userAccountMap" 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集合的映射 -->
<!-- 一对多的关系映射:配置封装account的内容
select属性指定的内容:查询账户的唯一标识:
column属性指定的内容:用户根据id查询账户时,所需要的参数的值(resultMap中id项的column)
property为user实体类中有关association的实体类的名称
ofType表示association中实体类的类型
-->
<collection property="accounts" ofType="account" select="com.itheima.dao.IAccountDao.findAccountByUid" column="id"></collection>
</resultMap>
<!-- 查询所有 一对多用到的-->
<select id="findAll" resultMap="userAccountMap">
select * from user
</select>
<!-- 根据id查询用户 一对一用到的-->
<select id="findById" parameterType="INT" resultType="user">
select * from user where id = #{uid}
</select>
</mapper>实体类
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//一个账户对应一个用户,一对一
// 从表实体应该包含一个主表实体的对象引用
private User user;
}测试类
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
//注意看,这里我们查询了,account 单没有 用他的user变量
List<Account> accounts = accountDao.findAll();
// for(Account account : accounts){
// System.out.println("--------每个account的信息------------");
// System.out.println(account);
// System.out.println(account.getUser());
// }
}控制台输出
和测试1相比只是释放了遍历
/**
* 测试查询所有
*/
@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
for(Account account : accounts){
System.out.println("--------每个account的信息------------");
System.out.println(account);
System.out.println(account.getUser());
}
}
当遍历到user的时候,框架会通过account类的id开始去查询user,并完成封装 ,这就是懒加载
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论