Mybatis的懒加载
1.最近在最账单加载时用到了懒加载,记录一下
1.mybatis提供了懒加载
1.修改配置配置文件
<settings>
<!-- 打开延迟加载的开关 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 将积极加载改为消极加载,即延迟加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
2.resultMap支持懒加载
association
<resultMap id="BaseResultMapLazy" type="com.ls.po.ItemLazyVo" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="title" property="title" jdbcType="VARCHAR" />
<result column="sell_point" property="sellPoint" jdbcType="VARCHAR" />
<result column="price" property="price" jdbcType="DECIMAL" />
<result column="num" property="num" jdbcType="INTEGER" />
<result column="brand" property="brand" jdbcType="VARCHAR" />
<result column="barcode" property="barcode" jdbcType="VARCHAR" />
<result column="image" property="image" jdbcType="VARCHAR" />
<result column="cid" property="cid" jdbcType="BIGINT" />
<result column="status" property="status" jdbcType="TINYINT" />
<result column="created" property="created" jdbcType="TIMESTAMP" />
<result column="updated" property="updated" jdbcType="TIMESTAMP" />
<association property="reptile" javaType="com.ls.po.Reptile"
<!--懒加载的这里-->
select="com.ls.dao.ReptileDao.selectById" column="id">
</association>
</resultMap>
<select id="findOrdersUserLazyLoading" resultMap="BaseResultMapLazy">
select * from tb_item
</select>
collection
<resultMap id="BaseResultMapLazy" type="com.ls.po.ItemLazyVo" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="title" property="title" jdbcType="VARCHAR" />
<result column="sell_point" property="sellPoint" jdbcType="VARCHAR" />
<result column="price" property="price" jdbcType="DECIMAL" />
<result column="num" property="num" jdbcType="INTEGER" />
<result column="brand" property="brand" jdbcType="VARCHAR" />
<result column="barcode" property="barcode" jdbcType="VARCHAR" />
<result column="image" property="image" jdbcType="VARCHAR" />
<result column="cid" property="cid" jdbcType="BIGINT" />
<result column="status" property="status" jdbcType="TINYINT" />
<result column="created" property="created" jdbcType="TIMESTAMP" />
<result column="updated" property="updated" jdbcType="TIMESTAMP" />
<collection property="reptile" ofType="com.ls.po.Reptile"
select="com.ls.dao.ReptileDao.selectById" column="id">
</collection>
</resultMap>
<mapper namespace="com.ls.dao.ReptileDao">
<select id="selectById" resultType="com.ls.po.Reptile">
select * from reptile where id=#{id}
</select>
</mapper>
3.然后写Dao,我这边就不写了
4.测试
@Test
public void queryListLazy(){
List<ItemLazyVo> ordersUserLazyLoading = itemDao.findOrdersUserLazyLoading();
//遍历上边的订单列表
for(ItemLazyVo orders : ordersUserLazyLoading) {
//执行getUser()去查询用户信息,这里实现按需加载
Reptile reptile = orders.getReptile();
System.out.println(reptile);
}
}
结果
至此已实现懒加载
详情请参加:
https://mybatis.org/mybatis-3/zh/index.html
https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache