mybatis plus多对多

数据库

sc

CREATE TABLE `sc` (
  `xh` varchar(10) NOT NULL DEFAULT '',
  `kcdh` varchar(10) NOT NULL DEFAULT '',
  `cj` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`xh`,`kcdh`) USING BTREE,
  KEY `sc_ibfk_2` (`kcdh`),
  CONSTRAINT `sc_ibfk_1` FOREIGN KEY (`xh`) REFERENCES `student` (`xh`),
  CONSTRAINT `sc_ibfk_2` FOREIGN KEY (`kcdh`) REFERENCES `course` (`kcdh`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

其他的和下面pojo差不多。

pojo

student

@Data
@TableName("student")
public class Student {
    @TableId
    String xh;
   // List<Sc> scs;
}

Course

@Data
@TableName("course")
public class Course {
    @TableId
    String kcdh;//课程代号
    List<Sc> scs;
}

Sc

@Data
@TableName("sc")
public class Sc {
    String kcdh;
    String xh;
    
    Student student;
    Course course;
}

mapper

ScMapper

column数据库表字段名称
propertyjava类的属性名称
javaTypejava类属性的类型

这里的one注解相当于把xh当参数去查询,结果注入到java属性student中

@Repository
public interface ScMapper  extends BaseMapper<Sc> {
    //sc建立与学生的多对一关系
    @Select("select * from sc where kcdh=#{kcdh}")
    @Results({
            @Result(property = "xh",column = "xh"),
            @Result(property = "student",column = "xh",one=@One(select = "com.example.emis10.mapper.StudentMapper.selectByXh"))
    })
    public List<Sc> listByCourse(String kcdh);
}

CourseMapper

//course建立与sc的一对多关系
@Select("select * from course")
@Results({
        @Result(property = "kcdh",column = "kcdh"),
        @Result(property = "scs",column = "kcdh",javaType = List.class,many = @Many(select = "com.example.emis10.mapper.ScMapper.listByCourse"))
})
public List<Course> list();

注意

  1. 这里是通过sc表与学生表建立多对一的关系,再通过course表与sc表建立一对多的关系,来间接达到student表与course表的多对多关系
  2. 使用上要注意方法的参数,如果要通过student的学号来查询对应的多对多关系,可能需要反着写一遍
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值