关于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>