开启提早加载
#提早加载总开关
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,并实现封装 ,这就是懒加载
发表回复