MyBatis框架的 resultMap(自连接,一对多,多对多)映射

来源:互联网 发布:linux系统管理员证书 编辑:程序博客网 时间:2024/06/05 21:31
多对多
在这个多对多的映射中,是通过3个表进行的连接,其实剖析内层还是一对多的关系,只是多添加一个表,把彼此的关系填上,根据id
进行的查询 ,映射。
首先我们的表结构是 学生表,教师表,还有一个关联表
首先1个老师可以教多个学生,一个学生也可以被多老师教,所以个表的关系是1号老师教1号和2号学生
1号 学生也可以被1号2号老师教。
对于这个多对多的映射 我们首先要有和思路就是
他返回的是一个对象 我们查的是老师的表,所有我们的实体类在老师表中有一个关联学生表的列
private Student stu;并把他们set出来
接下来我们知道了他的接口中方法应该写成public Teacher teacherbystudentid(int tid);并且是根据老师的id查的
接下来是小配置,在小配置中是我们最麻烦的地方,我们需要用resultMap映射
我们首先要链表查询 根据老师id查询出对应的学生名字  如下是查询语句。。。。。
然后我们返回的类型是resultMap并在里面写对于的表结构
如:id  name。。。。
首先是Teacher表的映射 返回的类型是Teacher,然后我们在里面用collection进行嵌套 的写 把Student表的列写出来,你也可以不用
这种方法,方法很多种,看你心情就好,返回会的类型是Studnet  然后就可以了,我们可以在测试类中进行测试 ,如果是对的我们可以吧
学生的姓名和老师的姓名都输出来、
<mapper namespace="cn.happy.dao.ITeacher"><resultMap id="MapStudentByTeacher" type="teacher">    <id column="tid" property="tid"></id>    <result column="tname" property="tname"/>    <collection property="stu" ofType="student">        <id property="sid" column="sid"></id>        <result property="sname" column="sname"></result>    </collection></resultMap><select id="GetStudentByTeacher" resultMap="MapStudentByTeacher">    SELECT sname,tname,sid,tid FROM student,teacher,teacher_student    WHERE student.sid=teacher_student.studentid AND teacher.tid=teacher_student.teacherid    AND tid=#{tid}</select></mapper>
事实上一对多和多对多没什么区别
    <select id="findByselectSLL" resultMap="mappercloo">    SELECT  name,empname,password FROM department, employee    WHERE department.id=employee.department_id AND department.id=#{id}</select>
<resultMap id="mappercloo" type="Dept"><id column="id" property="id"></id>    <result column="name" property="name"></result>    <collection property="emploa" ofType="employee">        <id column="empid" property="empid"></id>        <result column="empname" property="empname"></result>        <result column="department_id" property="department_id"></result>        <result column="password" property="password"></result>    </collection></resultMap>
这个是一对多的案例,对于那些接口实现类什么的我就不写了
可以实现的结果就是:一个部门可以有很多员工,我们可以查询出这个部门及其
所有的员工,在公司我们多用的都是一对多,所有要熟练掌握,,
还有一个就是自连接
自连接说白了就是自己调用自己
一个方法他有很多的下枝节 所以他需要自连接根据获取到的id进行查询 无极限的
查询,我们就可以用这种简单的代码进行实现。
    <resultMap id="getByCate" type="categoty">        <id column="cid" property="cid"></id>        <result column="cname" property="cname"></result>        <collection property="cates" ofType="categoty" select="cateById" column="cid"></collection>    </resultMap>    <select id="cateById" resultMap="getByCate">      select cid,cname,pid from category where pid=#{pid}    </select>
public List<Category> cateById(Integer pid);
首先 这个自连接查询的多条数据所以返回的是集合 并且他是根据每次获取的id
进行的查询,所以我们的方法如上:
然后是查询语句根据特定id进行的查询  我们这个只有一个表,映射的类型
是resultMap先写上 表结构,返回的类型是实体类
重点是Collection我们在实体类中返回的也是集合,2个特定类型我就不说了,
自己查,主要的是select 和
column  : 、、、select 是你下一个的查询SQL语句
column  是你要查的id 是根据这个id进行查的
因为我们的select 是我们之前的方法所有我们这个整体就一个方法,
一直在自己调自己,直到没有东西可查才结束,自连接就是这样。好了就这些,
再见。。。。


阅读全文
0 0
原创粉丝点击