以案例说明(以下案例代码都敲过验证过)
多对一(多个学生对一个老师 即学生集合中都存一个老师对象)
Mybatis多对一实现方式1:
//定义Student 和 Teacher 实体 @Data public class Student { private int id; private String name; //tid对应teacher的id private int tid; private Teacher teacher; } @Data public class Teacher { private int id; private String name; }
<mapper namespace="mapper.StudentMapper"> <resultMap id="stuAboutTea" type="bean.Student"> <result property="id" column="ic"></result> <result property="name" column="name"></result> //普通查询只需查询selectstudent就好了 //多对一查询多了association标签 我认为这个标签作用就是嵌套查询 //其中javaType是property中teacher对象的类 select嵌套查询的id <association property="teacher" column="tid" javaType="bean.Teacher" select="selectstubyid"/> </resultMap> <select id="selectstudent" resultMap="stuAboutTea"> select * from student </select> <select id="selectstubyid" resultType="bean.Teacher"> select * from teacher where id=#{id} </select> </mapper>
这种方式调selectid为selectstudent的sql selectstudent中就嵌套了selectstubyid的查询 嵌套的结果集存在private Teacher teacher;
Mybatis多对一实现方式2:
<resultMap id="StudentTeacher2" type="bean.Student"> <id property="id" column="sid"/> <result property="name" column="sname"/> <!--关联对象property 关联对象在Student实体类中的属性--> <association property="teacher" javaType="bean.Teacher"> <result property="name" column="tname"/> </association> </resultMap> <select id="getStudents2" resultMap="StudentTeacher2" > select s.id sid, s.name sname , t.name tname from student s,teacher t where s.tid = t.id </select>
这种方式是直接用sql将多对一的结果查询出来 需存到teacher对象中的参数映射在association标签中定义
我个人认为第二种更好一点 因为遇到复杂的sql更直观
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
一对多(一个老师对一个学生 即teacher实体类中存了student集合对象)
Mybatis一对多实现方式1:
@Data public class Teacher { private int id; private String name; //一个老师多个学生 private List<Student> students; } @Data public class Student { private int id; private String name; //tid对应teacher的id private int tid; }
<resultMap id="TeacherStudent" type="bean.Teacher"> <result property="name" column="tname"/> //collection标签同上例类似 但它是存student集合的 collection就是集合很好记 <collection property="students" ofType="bean.Student"> <result property="id" column="sid" /> <result property="name" column="sname" /> <result property="tid" column="tid" /> </collection> </resultMap> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid, s.name sname , t.name tname, t.id tid from student s,teacher t where s.tid = t.id and t.id=#{id} </select>
一对多例子同上类似 只不过将查询多对一中存单个对象变为存集合 标签collection就是集合