学习mybatis多对多注解,记录下来以便日后查询。
这里多对多关系用到了学生(student)和课程(course),一个学生可以选多门课,一门课可以被多名学生选择,中间表stu_cou.
Student.java
public class Student {
private int id;
private String name;
private Classes classes;
private List<Course> courseList;
//getter and setter
}
Course.java
public class Course {
private int id;
private String name;
private int credit;
private List<Student> studentList;
//getter and setter
}
StudentMapper.java,在其中添加通过courseId查询student的select语句:
@Select("select * from student where id in(select stu_id from stu_cou where cou_id=#{courseId})")
@Results({
@Result(id=true,property="id",column="id"),
@Result(property="name",column="name"),
@Result(property="classes",column="classes_id",javaType=Classes.class,
one=@One(select="com.lsj.test.mybatis.annotation.mapper.ClassesMapper.selectClasses",fetchType=FetchType.LAZY)),
@Result(property="courseList",column="id",many=@Many(select="com.lsj.test.mybatis.annotation.mapper.CourseMapper.selectCourseByStudent",fetchType=FetchType.LAZY))
})
public List<Student> selectStudentByCourse(int courseId);
CourseMapper.java中添加通过学生Id查询Course的select语句
@Select("select * from course where id in(select cou_id from stu_cou where stu_id=#{studentId})")
@Results({
@Result(id=true,property="id",column="id"),
@Result(property="name",column="name"),
@Result(property="credit",column="credit"),
@Result(property="studentList",column="id",
many=@Many(select="com.lsj.test.mybatis.annotation.mapper.StudentMapper.selectStudentByCourse",fetchType=FetchType.LAZY))
})
public List<Course> selectCourseByStudent(int studentId);
之后在StudentMapper.java中的select语句中的Result添加many,指向CourseMapper中的通过学生Id查询Course的select语句,同理CourseMapper也是一样的操作指向StudentMapper。
@Select("select * from student where id=#{id}")
@Results({
@Result(id=true,property="id",column="id"),
@Result(property="name",column="name"),
@Result(property="classes",column="classes_id",javaType=Classes.class,
one=@One(select="com.lsj.test.mybatis.annotation.mapper.ClassesMapper.selectClasses")),
//这里添加many,指向CourseMapper中的selectCourseByStudent查询语句
@Result(property="courseList",column="id",many=@Many(select="com.lsj.test.mybatis.annotation.mapper.CourseMapper.selectCourseByStudent",fetchType=FetchType.LAZY))
})
public Student selectStudent(int id);