1.一对一关联
MyBatis中使用association标签来解决一对一的关联查询,association标签可用的属性如下:
- property:对象属性的名称
- javaType:对象属性的类型
- column:所对应的外键字段名称
- select:使用另一个查询封装的结果
方法1:使用嵌套结果映射来处理,封装联表查询的结果
<select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id} </select> <!-- 使用resultMap映射实体类和字段之间的一一对应关系 --> <resultMap type="me.gacl.domain.Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="me.gacl.domain.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap>
方法2:嵌套查询,通过执行另一个SQL映射语句来返回预期的复杂类型
<select id="getClass2" parameterType="int" resultMap="ClassResultMap2"> select * from class where c_id=#{id} </select> <!-- 使用resultMap映射实体类和字段之间的一一对应关系 --> <resultMap type="me.gacl.domain.Classes" id="ClassResultMap2"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" select="getTeacher"/> </resultMap> <select id="getTeacher" parameterType="int" resultType="me.gacl.domain.Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select>
2.一对多关联
MyBatis中使用collection标签来解决一对多的关联查询,ofType属性指定集合中元素的对象类型
方法1:嵌套结果,使用嵌套结果映射来处理重复的联合结果的子集
<select id="getClass3" parameterType="int" resultMap="ClassResultMap3"> select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and c.c_id=#{id} </select> <resultMap type="me.gacl.domain.Classes" id="ClassResultMap3"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- ofType指定students集合中的对象类型 --> <collection property="students" ofType="me.gacl.domain.Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap>
方法2:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型
<select id="getClass4" parameterType="int" resultMap="ClassResultMap4"> select * from class where c_id=#{id} </select> <resultMap type="me.gacl.domain.Classes" id="ClassResultMap4"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher" select="getTeacher2"></association> <collection property="students" ofType="me.gacl.domain.Student" column="c_id" select="getStudent"></collection> </resultMap> <select id="getTeacher2" parameterType="int" resultType="me.gacl.domain.Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select> <select id="getStudent" parameterType="int" resultType="me.gacl.domain.Student"> SELECT s_id id, s_name name FROM student WHERE class_id=#{id} </select>