MyBatis 一对一关联映射,延迟加载lazy

一对一关联映射想要和延迟加载扯上关系,,那必然要实现嵌套查询。
需要用到association这个标签;

association元素是用来和一个复杂类型做关联的
常用属性
property:对应实体类中的属性名
javaType:属性对应的Java类型
resultMap:可以直接使用现有的resultMap,而不需要在这里配置
select:另一个查询映射的statement -> id,MyBatis会额外执行这个查询获取嵌套对象
column:列名,将主查询结果作为嵌套查询的参数,如:column = “{p = c}”,其中p为嵌套查询的参数
fetchType:数据加载方式,{lazy,eager},会覆盖lazyLoadingEnable配置

以用户(User)和购物车(Cart)为例

其中Cart里包含属性 user_id
User中包含属性cart

CartMapper.xml 中要有 根据user_id 查询 cart 的 select方法

<select id = "findCartByUserId" resultType = "com.entity.Cart">
	select * from cart where user_id = #{user_id}
</select>

UserMapper.xml 中关于resultMap的配置

<resultMap type = "com.entity.User" id = "userCartMap">
	<id property = "id" column = "id"/>
	...类属性与字段名的对应...
	...
	<association property = "cart"
	 column = "{user_id = id}" 
	 select = "com.mapper.CartMapper.findCartByUserId"/>
</resultMap>
<select id = "findUserAndCartById"
resultMap = "userCartMap">
	select * from user where id = #{id}
</select>

嵌套查询会多执行SQL,有时候我们只需要user,但是它会一块把cart也查出来,,
此时需要设置 associationfetchType 属性 为 lazy

其实延迟加载可以在MyBatis主配置文件中配置,,
相关 settings 设置如下

在这里插入图片描述
代码体现

<settings>
	<setting name = "lazyLoadingEnabled" value = "true"/>
	<setting name = "aggressiveLazyLoading" value = "false"/>
</settings>

延迟加载对象,当被调用其equals、hashCode、toString、clone方法时,才会加载该对象的数据

原创文章 10 获赞 10 访问量 443

猜你喜欢

转载自blog.csdn.net/weixin_43415201/article/details/105100535
今日推荐