实体类: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>