mybatis多表關聯查詢 - N+1次查詢+延遲加載

  •  對象一對一關聯

實體類:java

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.xmlsql

<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>
  • 關聯集合對象

 實體類:mybatis

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.xmlapp

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

ClassroomMapper.xmlspa

<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命令屢次,效率低。ssr

解決辦法:1.添加緩存;code

                2.開啓延時加載。xml

  • 延時加載配置:

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>
相關文章
相關標籤/搜索