Mybatis 多对多注解 查询

学习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);
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值