多对一:我的个人理解就是在类与类之间有has关系,解决的是sql查询时数据库内是外键关联的关系,teacher只有id与student对应,没有与id对应的值;用多对一来解决值得问题
多:student
@Data//lombok
public class Student {
private int id;
private String name;
private Teacher teacher;
}
一:teacher
@Data
public class Teacher {
private int ID;
private String name;
}
多个学生对应一个老师:
两种方式实现:
public interface StudentMapper {
List<Student> getAllStudent();//方法一
List<Student> getAllStudent2();//方法二
}
方法一对应的xml
<!-- 多对一 方式一 -->
<select id="getAllStudent" resultMap="SttudenttTeacher">
select * from student
</select>
<select id="getTeacherById" parameterType="_int" resultType="teacher">
select * from teacher where id=#{id};
</select>
<resultMap id="SttudenttTeacher" type="student">
<!-- property Student类的属性名 javaType 属性的类名 column 表内对应的列名 select 对应子查询的id-->
<association property="teacher" javaType="teacher" column="tid" select="getTeacherById"></association>
</resultMap>
方式二对应的xml:
<!-- 多对一 方式二-->
<select id="getAllStudent2" resultMap="SttudenttTeacher2">
select s.id id,s.name name,t.name tname from student s,teacher t where s.tid= t.id;
</select>
<resultMap id="SttudenttTeacher2" type="student">
<result property="id" column="id"></result>
<result property="name" column="name"></result>
<association property="teacher" javaType="teacher">
<result column="tname" property="name"></result>
</association>
</resultMap>