public class Student {
private int id;
private String name;
private int tid;}
public class TeacherOnetoMore {
private int id;
private String name;
private List<Student> students;}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cyk.dao.TeacherMapper">
<select id="getTeacherOnetoMore" resultType="TeacherOnetoMore">
select * from teacher;
</select>
<select id="getTeacherOnetoMoreById" resultMap="TeacherStudent">
SELECT s.id sid,s.name sname,t.id tid,t.name tname
FROM student s,teacher t
where s.tid = t.id and t.id = #{id}
</select>
<resultMap id="TeacherStudent" type="TeacherOnetoMore">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<select id="getTeacherOnetoMoreById2" resultMap="TeacherStudent2">
select * from teacher where id = #{id}
</select>
<resultMap id="TeacherStudent2" type="TeacherOnetoMore">
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacher"/>
</resultMap>
<select id="getStudentByTeacher" resultType="Student">
select * from student where tid = #{id}
</select>
</mapper>
javaType :用来指定实体类中属性的类型
ofType : 用来指定映射list或者集合中的pojo类型,泛型的约束类型;
这篇博客介绍了MyBatis中的映射配置文件,包括如何获取一对一关联关系的数据。通过`TeacherOnetoMore`类和`Student`类展示了教师与学生的一对多关系,并在XML映射文件中定义了查询语句和结果映射。`resultMap`元素用于定义复杂的结果映射,包括`collection`属性来处理一对多关联,而`ofType`用于指定集合中元素的类型。

被折叠的 条评论
为什么被折叠?



