一对多关联查询
xml方式
<select id="selectStudentByClassId" parameterType="Integer" resultType="com.Student">
select * from students where class_id = #{value} <!--根据classId查询该班所有学生-->
</select>
<resultMap id="selectClassById" type="com.Clazz"> <!--返回Class对象-->
<id property="classId" column="class_id"/> <!--只需要映射主键,其他会自动填充-->
<collection property="students" column="class_id" select="student.selectStudentByClassId"/>
<!--集合属性需要使用collection标签映射-->
<!--select属性指定其他查询SQL,并且会自动传递当前字段为关联字段,以集合形式回填入Class对象的students属性中-->
<!--select属性值带有命名空间,所以可以是其他映射文件中的查询语句-->
</resultMap>
<select id="selectClassById" parameterType="Integer" resultMap="selectClassById">
select * from classes where class_id = #{value} <!--根据classId查询该班级信息,并且使用resultMap映射-->
</select>
用于测试的关键代码片段,sqlSession
为创建的SqlSession
对象,其他代码省略
Clazz clazz = sqlSession.selectOne("student.selectClassById", 1);
System.out.println(clazz);
注解方式
package com;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
public interface StudentMapper {
@Select("select * from students where class_id = #{classId}")
Student selectStudentByClassId(Integer classId);
@Select("select * from classes where class_id = #{classId}")
@Results({
@Result(property = "classId", column = "class_id", id = true),
@Result(property = "students", column = "class_id", many = @Many(select = "com.StudentMapper.selectStudentByClassId"))
//many属性指定多的一方,@Man注解中的select属性指定要调用的方法名,省略包名和接口名会从该接口中找
})
Clazz selectClassById(Integer classId);
}
用于测试的关键代码片段,sqlSession
为创建的SqlSession
对象,其他代码省略
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Clazz clazz = studentMapper.selectClassById(1);
System.out.println(clazz);
Comments NOTHING