MyBatis的延迟加载(一对多查询案例)
1.什么是延迟加载?
开启延迟加载后,在真正使用数据的时候才发起级联查询,不用的时候不查询。
2.pojo
User类:
package com.wt.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//加入List<Account>存储用户所拥有的账户
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 Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", accounts=" + accounts +
'}';
}
}
Account类:略
3.mapper
UserDao:
public interface UserDao {
public List<User> findAll();
}
AccountDao:
public interface AccountDao {
Account findAccountById(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">
<mapper namespace="com.wt.dao.UserDao">
<resultMap type="User" id="findAllResultMap">
<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="accounts" ofType="Account"
select="com.by.dao.AccountDao.findAccountById" column="id"
fetchType="lazy">
</collection>
</resultMap>
<select id="findAll" resultMap="findAllResultMap">
select * from user
</select>
</mapper>
AccountDao.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.wt.dao.AccountDao">
<select id="findAccountById" parameterType="int" resultType="account">
select * from account where uid = #{id}
</select>
</mapper>
4.测试
@Test
public void testFindAll() {
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.findAll();
for(User user : userList){
System.out.println(user.getUsername());//不查询account
System.out.println(user.getAccounts());//查询account
}
}
5.结果
不查询Account:
查询Account: