MyBatis的延迟加载

8 篇文章 0 订阅

延迟加载:在需要用到数据时才进行加载,不需要用到数据时就不加载数据,延迟加载也称为懒加载。
立即加载:不管用不用,只要一调用方法,马上发送查询。
在对应的四种表关系中,一对多,多对一,一对一,多对多。
一对多,多对多:通常情况下采用延迟加载
多对一,一对一:通常情况下采用立即加载
延迟加载:
好处:先从单表查询,需要时再从关联表进行关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
坏处:因为只有需要用到数据时,才会进行数据库查询,这样在大批量数据查询时,因为查询工作也要消耗时间,所以可能造成用户等待时间变长,造成用户体验下降。

/**
	MyBatis-config.xml(使用assocation实现延迟加载)
**/
<!--开启延迟加载的支持-->
<settings>
	<!--打开延迟加载的开关-->
	<setting name="lazyLoadingEnabled" value="true"/>
	<!--将积极加载改为消息加载即按需加载-->
	<setting name="agressiveLazyLoading" value="false"/>
<settings>
/**一对一**/
public interface accountDao{
	List<Account> findAll();
}
/**AccountDao.xml**/
<mapper namespace="com.it.dao.AccountDao">
	<resultMap type="account" id="accountMap">
		<id column="aid" property="id"/>
		<result column="uid" property="uid"/>
		<result column="money" property="money"/>
		<!--它是用于指定从表方的引用实体属性的
		select:填写要调用的select映射的id
		column:填写要调用的select映射的参数-->
		<association property="user" javaType="User" 	select="com.it.dao.UserDao.findById" column="uid"/>
	</resultMap>
	<select id="findAll" resultMap="accountMap">
		select * from account
	</select>
</mapper>

public interface UserDao{
	User findById(Integer userId);
}

/**UserDao.xml**/
<mapper namespace="com.it.dao.UserDao">
	<select id="findById" resultType="User" parameterType="Integer">
		select * from user where id=#{uid}
	</select>
</mapper>
/**测试类**/
public void testFindAll(){
	Listr<Account> accountList = accountDao.findAll();
}
/**
 MyBatis-config.xml(使用assocation实现延迟加载)
**/
<!--开启延迟加载的支持-->
<settings>
 <!--打开延迟加载的开关-->
 <setting name="lazyLoadingEnabled" value="true"/>
 <!--将积极加载改为消息加载即按需加载-->
 <setting name="agressiveLazyLoading" value="false"/>
<settings>
/**一对多**/
public class User implements Serializable{
	private Integer id;
	private String username;
	private String sex;
	private List<Account> accountList;
	/**setter**/
	/**getter**/
}
/**UserDao.xml**/
<resultMap type="user" id="userMap">
	<id column="id" property="id"/>
	<result column="username" property="username"/>
	<result column="sex" property="sex"/>
	<!--select是用于指定查询账户的唯一标识
	    column:指定哪个字段的值作为条件查询-->
	<collection property="accountList" ofType="account"
	select="com.it.dao.AccountDao.findByUid" column="id">
	</collection>
</resultMap>	
<select id="findAll" resultMap="userMap">
	select * from user
</select>

public interface UserDao{
	List<User> findAll();
}

public interface AccountDao{
	List<Account> findByUid(Integer uid);
}

/**AccountDao.xml**/
<select id="findByUid" resultType="Account" parameterType="Integer">
	select * from account where uid=#{uid}
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值