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