嵌套查询与嵌套结果

嵌套查询

嵌套查询是指在查询过程中,嵌套其他查询语句进行相关属性的查询,可以用于ResultMap的collection、asscoiation等属性中。

下述测试案例中,在查询student的同时,通过嵌套查询获得了学生上过的学校。

测试类:

public class Student {
    private int id;
    private List<School> schoolList;
}

public class School {
    private int id;
    private String name;
}

xml:

<resultMap id="testMap" type="Student">
    <id property="id" column="id"/>
    <collection property="schoolList" column="id" ofType="school"
                <!-- 嵌套的查询语句 -->
                select="com.springboot2.mapper.TestMapper.getSchoolListById"/>
</resultMap>
<select id="test" resultMap="testMap">
    select id
    from student
</select>

<select id="getSchoolListById" resultType="School">
    select *
    from school
    where student_id=#{id}
</select>

测试代码:

void test() {
    Student student = testMapper.test();
    System.out.println(student);
}

结果:Student(id=1, schoolList=[School(id=1, name=a), School(id=2, name=b)])

嵌套结果

将查询结果映射到子属性中,只执行了一次sql,一般是多表联合查询

测试类同上

xml:

<resultMap id="testMap" type="Student">
    <id property="id" column="student_id"/>
    <!-- 嵌套的查询结果 -->
    <collection property="schoolList" column="id" ofType="school">
        <id property="id" column="school_id"/>
        <result property="name" column="school_name"/>
    </collection>
</resultMap>
<select id="test" resultMap="testMap">
    select student.id student_id, school.id school_id, school.name school_name
    from student
    left join school
    on student.id = school.student_id
</select>

结果:Student(id=1, schoolList=[School(id=1, name=a), School(id=2, name=b)])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值