mybaties多对一以及一对多的查询处理

今天学习mybaties时学到了当使用mybaties查询多对一的结果时怎么处理。
当我们要执行查询语句

select s.id ,s.name ,t.name  from student s,teacher t where s.tid = t.id

时,会发现其查询使用的参数包含在student和teacher两个对象里面,这种情况下我们的resultType填写student时会无法获取到teacher对象的参数,所以我们采用结果映射嵌套的办法,将teacher对象里面的参数映射出来

<!--
    在查询结果中含有其他类的属性时怎么办?(student类中含有teacher对象,要查询的结果为student的id student的name teacher的name)
    1.通过结果集映射resultMap写出各个结果映射result 当轮到写teacher对象的结果映射时不用result 用association 在其中嵌套result 写明映射关系
-->
    <resultMap id="teacherStudent" type="com.zyy.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.zyy.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>
    <select id="getStudentList" resultMap="teacherStudent" >
        select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid = t.id
    </select>

以下是多对一的处理

<resultMap id="teacherStudent" type="com.zyy.pojo.Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="studentList" ofType="com.zyy.pojo.Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
    </resultMap>
    <select id="getTeacher" resultMap="teacherStudent">
        select t.id tid,t.name tname,s.id sid,s.name sname from student_teather.teacher t,student_teather.student s where t.id=s.tid and t.id=1;
    </select>

注意一对多的时候因为参数为对象所以使用

		<association property="teacher" javaType="com.zyy.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>

然后一对多的时候因为参数为List集合所以使用

		<collection property="studentList" ofType="com.zyy.pojo.Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>

注意这两者申明类型的区别

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值