-
对象一对一关联
实体类:
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>