Mybatis高级映射之嵌套查询和嵌套结果的区别
概念嵌套查询是指通过执行另外一条SQL映射语句来返回预期的复杂类型;嵌套结果是使用嵌套结果映射来处理重复的联合结果的子集。开发人员可以使用上述任意一种方式实现对关联关系的加载。理解看完上面的解释是不是还是一脸懵逼,那么我们用通俗的语言来解释下,上图!何时使用?举个栗子假设,我们有一个学生的vo类,里面包含了学生的基本信息和班级信息嵌套查询:当查询完所有student后,再用c_id去查对应的cla
·
概念
嵌套查询是指通过执行另外一条SQL映射语句来返回预期的复杂类型;
嵌套结果是使用嵌套结果映射来处理重复的联合结果的子集。开发人员可以使用上述任意一种方式实现对关联关系的加载。
理解
看完上面的解释是不是还是一脸懵逼,那么我们用通俗的语言来解释下,上图!
何时使用?
举个栗子
假设,我们有一个学生的vo类,里面包含了学生的基本信息和班级信息
嵌套查询:
当查询完所有student后,再用c_id去查对应的class(mybatis对c_id进行了去重优化,不必每个student都查一次class,但效率仍然比较低,所以不推荐数据大时使用)
<!--嵌套查询 查询效率低 要多查一轮-->
<select id="getStudent" resultMap="studentvo">
select * from student
</select>
<resultMap id="studentvo" type="com.example.test.MySelect.vo.StudentVO" autoMapping="true">
<association property="c" column="c_id" select="getClass" ></association>
</resultMap>
<select id="getClass" resultType="com.example.test.MySelect.entity.Class">
select * from class where id=#{id}
</select>
(推荐且常用)嵌套结果1:
<!--嵌套结果-->
<resultMap id="studentvo" type="com.example.test.MySelect.vo.StudentVO">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
<!--方式1:缺点是要写每个字段一一对应-->
<association property="c" >
<id property="id" column="c_id"></id>
<result property="name" column="cname"></result>
</association>
<!--方式2:自动映射 *在没有相同字段*时可以使用!!-->
<!-- <association property="c" autoMapping="true"></association>-->
</resultMap>
(常用)嵌套结果2:
当ClassVO类中包含Student集合属性时
<select id="getAllClass" resultMap="allClassMap">
select c.* ,s.id as `sId`,s.name as `sName` from class c JOIN student s ON s.c_id=c.id
</select>
<resultMap id="allClassMap" type="com.example.test.MySelect.vo.ClassVO" >
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<collection property="students" ofType="com.example.test.MySelect.entity.Student" >
<id property="id" column="sId"></id>
<result property="name" column="sName"></result>
</collection>
</resultMap>
结语
你!
整明白了吗?
更多推荐
已为社区贡献1条内容
所有评论(0)