MyBatis多对一与一对多映射查询

实质上,无论是一对多还是多对一都是利用一个表查询共有属性,把共有属性传递到另一个表中进行查询。而这个过程关键也是利用resultMap这个标签来是实现的。

OneToMany

例子:

    <resultMap id="rmClass" type="com.imooc.mybatis.entity.Classes">
        <id column="id" property="id"></id>
        <result column="classno" property="classno"/>
        <collection property="studentList" select="student.selectByClassno"
                    column="classno"/>
    </resultMap>
    <select id="selectOneToMany" resultMap="rmClass" parameterType="String">
        select * from classes where name=#{value}
    </select>

id标签是class表的主键,
一对多的情况下使用collection标签,property是entity实体类中的查询出的studentList,select是student.xml定义的SQL名称,column则是传递的字段名。下方select则是定义查询的班级名称,可以此查出此班级下的学生信息。

多对一

<resultMap id="rmStudent" type="com.imooc.mybatis.entity.Student">
        <id column="id" property="id"/>
        <result column="classno" property="classno"/>
        <association property="classes" select="class.selectByClassno" column="classno"></association>
    </resultMap>
    <select id="selectManyToOne" resultMap="rmStudent" parameterType="String">
        select * from student where stuname=#{value}
    </select>

关于resultMap的使用大体同上,只是此时标签选择association。下方利用学生姓名可以查出班级信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值