mybatis处理一对多的查询
//查询出某个班级对应的所有老师和学生
1、使用嵌套结果
<select id="findClasses3" parameterType="int" resultMap="findClasses3Map"> select c.*,t.*,s.* from classes c,teacher t,student s where c.t_id = t.t_id and s.c_id = c.c_id and c.c_id = #{id} </select> <resultMap type="Classes" id="findClasses3Map"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <collection property="students" ofType="Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap>
使用collection节点对于list类型的返回使用ofType
2、使用嵌套查询
<select id="findClasses4" parameterType="int" resultMap="findClasses4Map"> select * from classes where c_id=#{id} </select> <resultMap type="Classes" id="findClasses4Map"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" select="findTeacher" column="t_id"> </association> <collection property="students" select="findStudents" column="c_id"></collection> </resultMap> <select id="findStudents" parameterType="int" resultType="Student"> select s_id id,s_name name from student where c_id = #{id} </select>
<select id="findTeacher" parameterType="int" resultType="Teacher"> select t_id id,t_name name from teacher where t_id = #{t_id} </select>
使用collection节点对于list返回直接用一个普通查询可以实现!
邮箱:wangh_2@sina.com