复制项目day03_eesy_03one2many到新建的项目day04_eesy_01lazy
1.删除项目中AccountUser类
2.IAccountDao接口中只保留findAll()
3.AccountTest类只保留testFindAll()
实现一对一延迟加载
4.更改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.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的内容-->
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="accountUserMap">
select * from account
</select>
</mapper>
5.测试AccountTest中的findAll方法
配置延迟加载
更改IAccountDao.xml
<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查询时,所需参数的值-->
<association property="user" column="uid" javaType="user" select="com.itheima.dao.IUserDao.findById"></association>
</resultMap>
此时执行testFindAll(),结果如下
并未实现一对一延迟加载
百度mybatis在xml中找到setting,更改SqlMapConfig.xml配置文件
<configuration><configuration>中加入下列配置
<!--配置参数-->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"></setting>
</settings>
测试结果
一对多情况下的延迟加载
1.IUserDao和IUserDao.xml
//根据id查询用户信息
User findById(Integer userId);
//IUserDao.xml
<!--根据id查询用户-->
<select id="findById" parameterType="INT" resultType="user">
select * from user where id=#{userId};
</select>
<!--配置user对象中accounts集合的映射,property是配置集合的名字ofType是集合元素类型accounts-->
<collection property="accounts" ofType="account" select="com.itheima.dao.IAccountDao.findAccountByUid" column="id">
</collection>
2. IAccountDao和IAccountDao.xml
//根据用户id查询账户信息
List<Account> findAccountByUid(Integer uid);
//IAccountDao.xml
<!--查询一条账户信息-->
<select id="findAccountByUid" resultType="account">
select * from account where id=#{uid}
</select>
3.测试,实现了一对多的延迟加载