在实际开发过程中,使用一对多查询的时候,只查询出一方,当程序中需要多方的数据时,mybatis再发出请求进行sql语句的查询。
例如:很多时候我们并不需要总是在加载用户信息时就一定要加载他的账户信息。这就是我们所说的延迟加载。
1、延迟加载和立即加载的区别
1.什么是延迟加载
在需要用到数据时才进行加载,不需要用到数据时就不加载数据。延迟加载也称懒加载。
2.什么是立即加载
不管用不用,只要一调用方法,马上发起查询。
3.实际应用
2、在mybatis中使用配置文件开发的时候,如何配置延迟加载。
2.1.在mybtis的主配置文件中添加 lazyLoadingEnabled和 aggressiveLazyLoading。
<settings>
<!--开启mybatis支持延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
2.2.在dao接口对应的映射配置文件中,添加(一对多)多对多的关系映射:配置封装user的内容
property属性:对应实体类的属性;
column属性:用户根据id查询时,所需要的参数的值;
select属性:查询用户的唯一标识;
offType属性:指定的是映射到list集合属性中pojo的类型。
<resultMap id="userMap" type="user"> <id property="id" column="id"></id> <result property="username" column="username"></result> <result property="birthday" column="birthday"></result> <result property="sex" column="sex"></result> <result property="address" column="address"></result> <collection property="accounts" column="id" ofType="com.dao.account" select="com.dao.AccountDao.findAccountByUid"></collection>
</resultMap>
3、在mybatis中使用注解开发时,如何配置延迟加载。
在mybtis 中的dao接口对应的方法中添加 Results注解,指定延迟加载的many 属性:
@Select("select * from user") @Results(id = "userMap",value = { @Result(id = true,property = "id",column = "id"), @Result(property = "username",column = "username"), @Result(property = "birthday",column = "birthday"), @Result(property = "sex",column = "sex"), @Result(property = "address",column = "address"), @Result(property = "accounts",column = "id",many = @Many(select = "com.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY)) }) List<User> findAll();