多对一处理
测试环境
1.导入Lombok
2.新建实体类Teacher,Student
3.建立TeacherMapper,StudentMapper接口
4.建立TeacherMapper.xml,StudentMapper.xml文件
5.在核心配置文件中绑定我们的Mapper接口或xml文件
6.测试
这是创建的两个表:
mysql> select * from teacher;
+----+----------+
| id | name |
+----+----------+
| 1 | Mr.Zhang |
+----+----------+
1 row in set (0.00 sec)
mysql> select * from student;
+----+----------+------+
| id | name | tid |
+----+----------+------+
| 1 | zhangSan | 1 |
| 2 | liSi | 1 |
| 3 | wangWu | 1 |
| 4 | zhaoLiuu | 1 |
+----+----------+------+
4 rows in set (0.00 sec)
这是实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
//学生需要关联一个老师
private Teacher teacher;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
按照查询嵌套处理
<!--按照查询嵌套-->
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id" />
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacherById"/>
</resultMap>
<select id="getTeacherById" resultType="Teacher">
select * from mybatis.teacher where id=#{id};
</select>
按照结果嵌套处理(推荐)
<!--按照结果嵌套-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid" />
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
一对多处理
比如:一个老师拥有多个学生,对于老师而言,就是一对多的关系。
这是实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private int tid;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
private List<Student> students;
}
按照结果嵌套处理(推荐)
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.id=t.id and t.id=#{tid};
</select>
<resultMap id="TeacherStudent" type="Teacher">
<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>
小结
1.关联------association------多对一
2.集合------collection------一对多
3.javaType & ofType
- javaType 用来指定实体类中属性的类型
- ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!