开启延迟加载后,在真正使用数据的时候才发起级联查询,不用的时候不查询。
在接口UserDao中封装一个方法:
public interface UserDao {
User getUserByid1(Integer id);
}
在对应的配置文件UserDao.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">
<!--namespace:唯一,接口全类名-->
<mapper namespace="com.by.dao.UserDao">
<resultMap id="getUserById1Result" type="user">
<id column="id" property="id"></id>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!--延迟加载的一对多-->
<!--
property:属性名
ofType:泛型 返回类型
select: 要调用的 select 映射的 id
column : 传递给 select 映射的参数
fetchType="lazy":懒加载,默认情况下是没有开启延迟加载的
-->
<collection property="account" ofType="account" select="com.by.dao.AccountMapper.selectAccountByUid"
column="id" fetchType="lazy" ></collection>
</resultMap>
<select id="getUserByid1" parameterType="int" resultMap="getUserById1Result">
SELECT *
FROM USER
WHERE id = #{id}
</select>
</mapper>
其中的select属性com.by.dao.AccountMapper是全类名,如果要查询用户的Account中的属性,sql语句要在AccountMapper.xml中写,selectAccountByUid是查询语句的ID值
<?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.by.dao.AccountMapper">
<select id="selectAccountByUid" parameterType="int" resultType="account">
select *
from account
WHERE uid = #{uid}
</select>
</mapper>
测试类:
public void testFindAll() throws IOException {
//返回接口的代理类
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user =userDao.getUserByid1(43);
System.out.println(user.getUsername());
List<Account> accountList = user.getAccount();
for (Account account:accountList){
System.out.println(account);
}
}