数据库
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 | 数据库表字段名称 |
---|---|
property | java类的属性名称 |
javaType | java类属性的类型 |
这里的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();
注意
- 这里是通过sc表与学生表建立多对一的关系,再通过course表与sc表建立一对多的关系,来间接达到student表与course表的多对多关系
- 使用上要注意方法的参数,如果要通过student的学号来查询对应的多对多关系,可能需要反着写一遍