通过前面的学习,我们已经掌握了MyBatis中一对一,一对多,多对多关系的配置及实现,可以实现对象的关联查询。实际开发过程中很多时候我们并不需要总是在加载用户信息时就一定要加载他的账户信息。此时就是我们所说的延迟加载。
1 何为延迟加载?
延迟加载:就是在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载. 好处:先从单表查询,需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
坏处:因为只有当需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。
2 实现需求
需求:查询账户(Account)信息并且关联查询用户(User)信息。如果先查询账户(Account)信息即可满足要求,当我们需要查询用户(User)信息时再查询用户(User)信息。把对用户(User)信息的按需去查询就是延迟加载。
MyBatis第三天实现多表操作时,我们使用了resultMap来实现一对一,一对多,多对多关系的操作。主要是通过association、collection实现一对一及一对多映射。association、collection具备延迟加载功能。
3 使用assocation实现延迟加载
需求:查询账户信息同时查询用户信息。
3.1 账户的持久层DAO接口和映射文件
/**
* <p>Title: IAccountDao</p>
* <p>Description: 账户的持久层接口</p>
* <p>Company: http://www.itheima.com/ </p>
*/
public interface IAccountDao {
/**
* 查询所有账户,同时获取账户的所属用户名称以及它的地址信息
* @return
*/
List<Account> findAll();
}
<?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">
<!-- 建立对应关系 -->
<resultMap type="account" id="accountMap">
<id column="aid" property="id" />
<result column="uid" property="uid" />
<result column="money" property="money" />
<!-- 它是用于指定从表方的引用实体属性的 -->
<association property="user" javaType="user"
select="com.itheima.dao.IUserDao.findById" column="uid">
</association>
</resultMap>
<select id="findAll" resultMap="accountMap">
select * from account
</select>
</mapper>
select
:填写我们要调用的select映射的id;column
:填写我们要传递给select映射的参数。
3.3 用户的持久层DAO接口和映射文件
/**
* <p>Title: IUserDao</p>
* <p>Description: 用户的业务层接口</p>
* <p>Company: http://www.itheima.com/ </p>
*/
public interface IUserDao {
/**
* 根据id查询
* @param userId
* @return
*/
User findById(Integer userId);
}
<?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.IUserDao">
<!-- 根据id查询 -->
<select id="findById" resultType="user" parameterType="int">
select * from user where id = #{uid}
</select>
</mapper>
3.4 开启MyBatis的延迟加载策略
进入MyBatis的官方文档,找到settings的说明信息:
我们需要在MyBatis的配置文件SqlMapConfig.xml文件中添加延迟加载的配置。
<!-- 开启延迟加载的支持 -->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
3.5 编写测试只查账户信息不查用户信息
/**
* <p>Title: MybastisCRUDTest</p>
* <p>Description: 一对多账户的操作</p>
* <p>Company: http://www.itheima.com/ </p>
*/
public class AccountTest {
private InputStream in ;
private SqlSessionFactory factory;
private SqlSession session;
private IAccountDao accountDao;
@Before//在测试方法执行之前执行
public void init()throws Exception {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3.创建SqlSession工厂对象
factory = builder.build(in);
//4.创建SqlSession对象
session = factory.openSession();
//5.创建Dao的代理对象
accountDao = session.getMapper(IAccountDao.class);
}
@Test
public void testFindAll() {
//6.执行操作
List<Account> accounts = accountDao.findAll();
}
@After//在测试方法执行完成之后执行
public void destroy() throws Exception{
//7.释放资源
session.close();
in.close();
}
}
测试结果如下:
我们发现,因为本次只是将Account对象查询出来放入List集合中,并没有涉及到User对象,所以就没有发出SQL语句查询账户所关联的User对象的查询。
4 使用Collection实现延迟加载
同样我们也可以在一对多关系配置的<collection>结点中配置延迟加载策略。<collection>结点中也有select属性,column属性。
需求:完成加载用户对象时,查询该用户所拥有的账户信息。
4.1 在User实体类中加入List<Account>属性
/**
* <p>Title: User</p>
* <p>Description: 用户的实体类</p>
* <p>Company: http://www.itheima.com/ </p>
*/
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
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 + "]";
}
}
4.2 编写用户和账户持久层接口的方法
/**
* 查询所有用户,同时获取出每个用户下的所有账户信息
* @return
*/
List<User> findAll();
/**
* 根据用户id查询账户信息
* @param uid
* @return
*/
List<Account> findByUid(Integer uid);
4.3 编写用户持久层映射配置
<resultMap type="user" id="userMap">
<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" />
<collection property="accounts" ofType="account"
select="com.itheima.dao.IAccountDao.findByUid" column="id">
</collection>
</resultMap>
<!-- 配置查询所有操作 -->
<select id="findAll" resultMap="userMap">
select * from user
</select>
collection
标签:一对多对应关系中的集合元素;ofType
属性:用于指定集合元素的数据类型;select
属性:是用于指定查询账户的SQL对应的方法(账户的DAO全限定类名加上方法名称);column
属性:是用于指定使用哪个字段的值作为条件查询。
4.4 编写账户持久层映射配置
<!-- 根据用户id查询账户信息 -->
<select id="findByUid" resultType="account" parameterType="int">
select * from account where uid = #{uid}
</select>
4.5 测试只加载用户信息
/**
* <p>Title: MybastisCRUDTest</p>
* <p>Description: 一对多的操作</p>
* <p>Company: http://www.itheima.com/ </p>
*/
public class UserTest {
private InputStream in ;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Before//在测试方法执行之前执行
public void init()throws Exception {
//1.读取配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3.创建SqlSession工厂对象
factory = builder.build(in);
//4.创建SqlSession对象
session = factory.openSession();
//5.创建Dao的代理对象
userDao = session.getMapper(IUserDao.class);
}
@Test
public void testFindAll() {
//6.执行操作
List<User> users = userDao.findAll();
}
@After//在测试方法执行完成之后执行
public void destroy() throws Exception{
session.commit();
//7.释放资源
session.close();
in.close();
}
}
测试结果如下:
我们发现并没有加载Account账户信息。