您的位置:首页 > 其它

mybatis延迟加载

2016-01-09 03:03 501 查看
mybatis延迟加载:延迟加载是先从单表去查询,使用到关联信息时再从关联表中查询信息。这样可以提高查询效率。

mybatis延迟加载需要配合association和collection标签,使用子查询去查询。

select t.*,
(select * from product_detail p where t.id = p.product_id)
from product t where t.id = 1


延迟加载只有resultMap可以。
即定义多个resultMap。在加载一个statment完成后再加载其他的statment(定义多个statment)。

例子:
<resultMap type="com.xy.domain.ProductDTO" id="productResult">
<id column="id" property= "id" />
<result column="product_name" property= "productName" />
<!--
调用其他的 statment
1.select默认从本 mapper.xml 中寻找,找不到需要指定全路径
-->
<association property="productDetail" column="id"
select="com.xy.mapper.ProductIndexMapper.getProductDetailByProductId" />
</resultMap>

<select id= "getProductById" parameterType ="int"
resultMap="productResult">
select p.id,
p.product_name
<where>
p.id = #{id}
</where>
</select>

<select id= "getProductDetailByProductId" parameterType= "int"
resultType="com.xy.domain.ProductDetail" >
select pd.id id,
pd.product_Id product_id,
pd.product_price,
pd.product_pic
from product_detail pd
<where>
pd.product_Id = #{value}
</where>
</select>
然后在mysql-config.xml中配置好延迟加载:
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
</settings>
这样配置好以后,调用getProductById时不会执行获取产品详情的sql,只有在使用getProductDetailList();的时候,才会加载下面的sql。这样只有用到了才加载。提高了数据库查询效率。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息