mybatis级联

关于mybatis级联问题

1、一对多

比如现在有这样俩个表
学生表
院系表
院系与学生是一对多的关系 院系表的主键是学生表的外键。所以在写pojo类的时候需要 增加一个list属性来存放相关级联表的属性。那么便可以编写相关的
mapper.xml文件。下面给出大致过程

<mapper namespace="DeptNS">

    <resultMap id="DeptMap" type="Dept" >
        <id column="dname" property="dName"></id>
        <result property="note" column="d_note" ></result>
        <collection property="list" column="dname" select="StudentNS.findStudentByDept" ></collection>
    </resultMap>


    <select id="findDept" parameterType="String" resultMap="DeptMap" >
        SELECT  * FROM  dept WHERE  dname=#{dname}
    </select>

</mapper>

这个是StudentNS.findStudentByDept

  <select id="findStudentByDept" parameterType="String" resultType="Student">
        SELECT  sno as "sno",s_name as "sName",s_age as "sAge",s_sex as "sSex",s_dept as "sDept" FROM  student WHERE  s_dept=#{deptName}
    </select>

2、一对一关联
现在还是以学生和学院表为例
需求是:在以学号查学生的同时,会同时查到外键关联的学员表
这时候我们 的关系就是一对一
首先写好pojo类。查询首先是根据sno查学生信息然后根据查到的s_dept 再去查dept表的内容最后封装为一个Student 对象。
mapper中主要用的association标签
映射器代码如下

<resultMap id="StudentMap" type="Student" >
        <id column="sno" property="sno"></id>
        <result property="sName" column="s_name" ></result>
        <result property="sAge" column="s_age" ></result>
        <result property="sSex" column="s_sex" ></result>
       <result property="sDept" column="s_dept"></result>
        <association property="dept" column="s_dept" select="DeptNS.findDeptOnly">

        </association>

   </resultMap>


    <select id="findStudent" parameterType="Integer"  resultMap="StudentMap">
        SELECT  sno,s_name ,s_age ,s_sex ,s_dept  FROM  student
              WHERE sno=#{id}

    </select>

    <select id="findDeptOnly" parameterType="string" resultType="Dept">
        SELECT  dname as "dName",d_note as "note" FROM  dept WHERE  dname=#{str}
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值