mybatis多表关联查询 - N+1次查询+延迟加载

本文介绍MyBatis中实现一对一双向关联的具体方法,包括如何通过XML配置文件进行关联映射,以及如何解决N+1次查询带来的效率问题,并提供了解决方案如添加缓存和开启延时加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  •  对象一对一关联

实体类:

public class Student {
	private int id;
	private String name;
	private int cid;
	private Classroom classroom;
        //略
}

public class Classroom {
	private int id;
	private String name;
        //略
}

ClassroomMapper.xml

	<select id="selById" resultType="Classroom" parameterType="int">
		select * from classroom where id=#{0}
	</select>

StudentMapper.xml

<resultMap type="Student" id="myresultmap">
		<id column="id" property="id"/>
		<result column="name" property="name"/>
		<result column="cid" property="cid"/>
		<!-- 在最终返回Student对象时,同时帮助去查询以下所关联的对象 -->
		<association property="classroom" select="a.b.selById" column="cid"></association>
</resultMap>
	<select id="selAll" resultMap="myresultmap">
		select * from student
	</select>
  • 关联集合对象

 实体类:

public class Classroom {
	private int id;
	private String name;
	private List<Student> list;
        //略
}

public class Student {
	private int id;
	private String name;
	private int cid;
        //略
}

StudentMapper.xml

	<select id="selByCid" resultType="Student" parameterType="int">
		select * from student where cid=#{0}
	</select>

ClassroomMapper.xml

	<resultMap type="Classroom" id="myresultmap1">
		<id column="id" property="id"/>
		<result column="name" property="name"/>
		<collection property="list" select="a.c.selByCid" column="id" ></collection>
	</resultMap>
	<select id="selAll3" resultMap="myresultmap1">
		select * from classroom
	</select>

 

N+1次查询执行sql命令多次,效率低。

解决办法:1.添加缓存;

                2.开启延时加载。

  • 延时加载配置:

mybatis默认没有开启延迟加载,需要在SqlMapConfig.xml中setting配置。

在mybatis核心配置文件中配置:lazyLoadingEnabled、aggressiveLazyLoading

设置项

描述

允许值

默认值

lazyLoadingEnabled

全局性设置懒加载。如果设为‘false’,则所有相关联的都会被初始化加载。

true | false

false

aggressiveLazyLoading

当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。

true | false

true

在SqlMapConfig.xml中配置:

<settings>
    <!-- 打开延迟加载的开关 -->
    <setting name="lazyLoadingEnabled" value="true"/>
    <!-- 将积极加载改为消极加载,即延迟加载 -->
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

 

转载于:https://my.oschina.net/gAKey/blog/1788133

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值