Mybatis对于延迟加载/懒加载的xml开发和注解开发的理解
个人见解:在多表查询中,只有当真正使用到表中的数据的时候,才发起表的查询。不使用不发起查询
XML文件的懒加载的条件:
- 需要将多表的SQL语句,拆分为单表的查询语句
- 每个SQL语句都要提供功能,使用查询传递的方式,完成对数据的关联查询
- 在核心配置文件中,添加
<settings>
标签
环境:
两个映射器(接口),核心配置文件,映射器的配置文件
public interface UserDao {
List<User> queryUserAll();
User findByAccountUid();
}
public interface AccountDao {
List<Account> queryAccountAll();
List<Account> findByUserId();
}
对一关系的查询:在AccountDao.xml文件中:使用select标签
<select id="queryAccountAll" resultMap="queryAccountAll">
select * from account
</select>
<resultMap id="queryAccountAll" type="account">
<id property="id" column="id"/>
<result property="uid" column="uid"/>
<result property="money" column="money"/>
<!-- association:对一关系的标签
property:关联的另一个javabean中的属性
javaType:关联的另一个javabean中属性的类型
select:关联另一个方法的位置
column:以account中的什么属性来进行关联 -->
<association property="user" javaType="user" select="UserDao.findByAccountUid" column="uid"/>
</resultMap>
另一个方法的提供:在UserDao.xml文件中:
<select id="findByAccountUid" resultType="user">
/* 根据select的属性值对应的方法,把uid的字段的值传递过来作为id的值进行查询 */
SELECT * from user where id = #{id}
</select>
核心配置文件的配置:
<settings>
<!--开启懒加载的全局开关-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--关闭积极加载,使用按需加载-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
即可完成对一关系的懒加载的功能,
而在对多的关系中:需要将标签<association >
更改为<collection>
完成对多关系的配置如下:
<!-- property:关联的另一个javabean中的属性
ofType:关联的另一个javabean中属性的类型
select:关联另一个方法的位置
column:以user中的什么属性来进行关联 -->
<collection property="accountList" ofType="account" select="AccountDao.findByUserId" column="id"/>
将表的关系更改之后:对于<select>
标签中的SQL语句,只需要更改就行.
注解使用
对一关系的注解开发:在对一关系的映射器中,这里是:Account接口
@Select("select * from account")
@Results({
@Result(property = "id", column = "id", id = true),
@Result(property = "uid", column = "uid"),
@Result(property = "money", column = "money"),
/*
另一个javaBean的属性配置
property:account中的javabean属性名
column:从哪个属性获取关联关系
@One:对一的关系注解
select:定位到另一个映射器的实现方法
fetchType:设置加载方式
*/
@Result(property = "user", column = "uid",
one = @One(select = "UserDao.queryUserById"
, fetchType = FetchType.LAZY)
)
})
List<Account> queryAllLazy();
在对一的关系中的另一个映射器中:
/*根据对于关系的传递过来的uid作为查询的id值*/
@Select("select * from user where id = #{id}")
User queryUserById(Integer id);
对多的关系注解开发:这里只粘贴表关系变化的不同的注解
/* 另一个javaBean的属性配置
property:account中的javabean属性名
column:从哪个属性获取关联关系
@Many:对一的关系注解
select:定位到另一个映射器的实现方法
fetchType:设置加载方式
*/
@Result( property = "accountList"
,column = "id"
,many = @Many(select = "AccountDao.queryAccount"
,fetchType = FetchType.LAZY))
另一个映射器中的代码:
/*根据传递过来的关系的id值作为查询的uid值*/
@Select("select * from account where uid = #{uid}")
List<Account> queryAccount();
以上就是我个人对于使用懒加载的简单的入门实例:
感叹:有个记载笔记的地方是很不错啊,有些忘了的时候,就过来翻一翻.不错!