Mybatis学习日志(一)
关联查询——一对一、一对多、多对多
下面写法为xml写法,注解写法参考:博客
一对一:
1.嵌套结果(resultMap+association)
注:该方法容易出错在实体类的构造函数与查询结果不匹配,尤其是无参构造
实例代码(班级查询带班主任信息)
<select id="getClassesById" resultMap="oneToOne"> select * from classes c,teacher t where c.teacher_id=t.tid and c.id=#{id} </select> <resultMap id="oneToOne" type="domain.Classes"> <id property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" javaType="domain.Teacher"> <id property="tid" column="tid"/> <result property="tname" column="tname"/> </association> </resultMap>
2.嵌套查询(resultMap+association,优先使用,优点是可以重复使用)
<select id="getClassesByIdNew" resultMap="myMap" parameterType="int"> select * from classes where id=#{id} </select> <select id="getTeacherById" resultType="domain.Teacher" parameterType="int"> select * from teacher where tid=#{tid} </select> <resultMap id="myMap" type="domain.Classes"> <association property="teacher" column="teacher_id" select="getTeacherById"></association> </resultMap>
一对多:(collection)
<select id="getClassesByIdAndStudents" resultMap="oneToMany" parameterType="int"> select * from classes where id=#{id} </select> <resultMap id="oneToMany" type="domain.Classes"> <id property="id" column="id"/> <result property="name" column="name"/> <collection property="students" column="id" select="dao.StudentDao.getStudentsByClassesId"></collection> <collection property="teacher" column="teacher_id" select="getTeacherById"></collection> </resultMap>
property:一对多的“多”方,在实体类中的属性。
column:一对多的“多”方,在数据库中对应的字段名称。
select:代表二次查询,若在同一个文件,则只需要写方法名字;若不在同一个文件,则需要写“全类名.方法名”
多对多:
通常在数据库中增加关系表(中间表),并且不需要建立实体类。
比如:查询所有学生的所有所选课程。
数据库中建立学生表,课程表,学生选课表
Mybatis中建立学生表和课程表即可,在学生表中存入课程集合,并不需要建立学生选课表
way1:嵌套结果
<select id="getStudentsCourses" resultMap="manyToMany"> select * from student as s,course as c,course_selection as cs where cs.cid=c.course_id and cs.sid=s.student_id </select> <resultMap id="manyToMany" type="domain.Student"> <id property="id" column="student_id"></id> <result property="cid" column="classes_id"></result> <result property="name" column="student_name"></result> <result property="sex" column="student_sex"></result> <collection property="courses" ofType="domain.Course"> <id property="id" column="course_id"></id> <result property="name" column="course_name"></result> </collection> </resultMap>
way2:嵌套查询
<select id="getStudentsCourseswithbyCourses" resultMap="MTM"> select * from student as s,course as c,course_selection as cs where cs.cid=c.course_id and cs.sid=s.student_id </select> <resultMap id="MTM" type="domain.Student"> <id property="id" column="student_id"></id> <result property="cid" column="classes_id"></result> <result property="name" column="student_name"></result> <result property="sex" column="student_sex"></result> <collection property="courses" column="course_id" select="dao.CourseDao.getCourseById"></collection> </resultMap>
【Over】

浙公网安备 33010602011771号