mybatis嵌套查询与子查询

多对一的查询处理

1.按照查询嵌套处理。将多表的数据分别查出来然后用resultMap对应起来
(复杂属性的字段使用association(对应对象)或者collection(对应集合)来映射)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gsy.dao.StudentMapper">
    <resultMap id="getS" type="com.gsy.pojo.Student">
        <association property="tid" column="tid" javaType="com.gsy.pojo.Teacher" select="getTea"/>
    </resultMap>
    <select id="getStudent" resultMap="getS">
        SELECT * from student
    </select>

    <select id="getTea" resultType="com.gsy.pojo.Teacher">
        SELECT * from teacher where id=#{tid}
    </select>
</mapper>

2.按照结果嵌套处理。将数据直接查询出来

    <select id="getS" resultMap="TaS">
        SELECT s.id sid,s.name sname,t.id tid,t.name tname
        from student s,teacher t
        where s.tid=t.id
    </select>
    <resultMap id="TaS" type="com.gsy.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="tid" javaType="com.gsy.pojo.Teacher">
            <result property="name" column="tname"/>
            <result property="id" column="tid"/>
        </association>
    </resultMap>

一对多的子查询处理

一对多的子查询使用collection来进行处理

    <select id="getTeacher2" resultMap="TS2">
        select * from teacher where id = #{tid};
    </select>
    <resultMap id="TS2" type="com.gsy.pojo.Teacher">
        <collection property="students" javaType="ArrayList" ofType="com.gsy.pojo.Student" select="getStuByTid" column="id"/>
    </resultMap>
    <select id="getStuByTid" resultType="com.gsy.pojo.Student">
        select * from student where tid = #{tid};
    </select>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值