SpringBoot-SpringData-ManyToMany

来源:互联网 发布:人工智能 04 哈工大 编辑:程序博客网 时间:2024/04/30 12:53

前面我们说了SpringData的@OneToOne : SpringBoot-SpringData-oneToOne
这节说一下@ManyToMany

多对多映射:一方实例可以获取多个对方实例引用,反之亦然


模型

以学生选课为模型,学生和选修课为多对多关系


项目结构

项目结构

学生类Student及StudentRepository
课程类Course及CourseRepository
测试类ManyToManyTest


Domain

学生类

@Entity@Table(name = "student")public class Student {    private String pid;    private String studentName;    private Set<Course> course;    //选修课程    public Student() {    }    public Student(String pid, String studentName, Set<Course> course) {        this.pid = pid;        this.studentName = studentName;        this.course = course;    }    @Id    @Column(name = "pid", unique = true, nullable = false, length = 32)    @GeneratedValue(generator = "generator")    @GenericGenerator(name = "generator", strategy = "uuid")    public String getPid() {        return pid;    }    @Column(name = "student_name", unique = true, length = 64)    public String getStudentName() {        return studentName;    }    /**     * Hibernate 会自动创建一张关系表stu_cou, 里边有俩字段stu_id和cou_idfen分别为两表主键     *     * @return     */    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.EAGER)    @JoinTable(name = "stu_cou", joinColumns = {@JoinColumn(name = "stu_id")}, inverseJoinColumns = {@JoinColumn(name = "cou_id")})    public Set<Course> getCourse() {        return course;    }    public void setPid(String pid) {        this.pid = pid;    }    public void setStudentName(String studentName) {        this.studentName = studentName;    }    public void setCourse(Set<Course> course) {        this.course = course;    }}

课程类

@Entity@Table(name = "course")public class Course implements java.io.Serializable {    private static final long serialVersionUID = 6398143635533582335L;    private String pid;    private String courseName;// 课程名称    private Set<Student> Student; // 选修课程学生    public Course() {    }    public Course(String pid, String courseName, Set<Student> student) {        this.pid = pid;        this.courseName = courseName;        this.Student = student;    }    @Id    @Column(name = "pid", unique = true, nullable = false, length = 32)    @GeneratedValue(generator = "generator")    @GenericGenerator(name = "generator", strategy = "uuid")    public String getPid() {        return pid;    }    @Column(name = "course_name", unique = true, length = 64)    public String getCourseName() {        return courseName;    }    //mappedBy :    //          表示当前所在表和 Student 的关系是定义在 Student 里面的 course 这个成员上面的,    //          他表示此表是一对一关系中的从表,也就是关系是在 Student 表中维护的,    //          Student 表是关系的维护者,有主导权,它有个外键指向 course (Student 中的 getCourse() )    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "course")    //NotFound : 意思是找不到引用的外键数据时忽略,NotFound默认是exception    @NotFound(action = NotFoundAction.IGNORE)    public Set<Student> getStudent() {        return Student;    }    public void setPid(String pid) {        this.pid = pid;    }    public void setCourseName(String courseName) {        this.courseName = courseName;    }    public void setStudent(Set<Student> student) {        Student = student;    }}

DAO

public interface StudentRepository extends JpaRepository<Student, Long> {    Student findByStudentName(String name);}public interface CourseRepository extends JpaRepository<Course, Long> {    Course findByCourseName(String name);}

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=123spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.jpa.properties.hibernate.hbm2ddl.auto=create-dropspring.jpa.show-sql=true

测试Test

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(DemoApplication.class)public class ManyToManyTest {    @Autowired    CourseRepository courseRepository;    @Autowired    StudentRepository studentRepository;    @Before    public void testData(){        //Course        Course course1 = new Course();        course1.setCourseName("course1");        Course course2 = new Course();        course2.setCourseName("course2");        Course course3 = new Course();        course3.setCourseName("course3");        courseRepository.save(course1);        courseRepository.save(course2);        courseRepository.save(course3);        //Student        Student student1 = new Student();        student1.setStudentName("Student1");        Student student2 = new Student();        student2.setStudentName("Student2");        Student student3 = new Student();        student3.setStudentName("Student3");        // 学生1 选修课程12        Set<Course> courses = null;        courses = new HashSet<>();        courses.add(course1);        courses.add(course2);        student1.setCourse(courses);        studentRepository.save(student1);        // 学生2 选修课程23        courses = new HashSet<>();        courses.add(course2);        courses.add(course3);        student2.setCourse(courses);        studentRepository.save(student2);    }    @Test    public void test() throws Exception {        //取学生        Student student1 = studentRepository.findByStudentName("Student1");        System.out.print("student1.getStudentName()" + student1.getStudentName());        //取课程        Course course2 = courseRepository.findByCourseName("course2");        System.out.print("course2.getCourseName()" + course2.getCourseName());    }}

测试结果

取学生获取课程实例:

取学生获取课程实例

取课程获取学生实例

取课程获取学生实例


SpringData自动创建的数据库

-- ------------------------------  Table structure for `course`-- ----------------------------DROP TABLE IF EXISTS `course`;CREATE TABLE `course` (  `pid` varchar(32) NOT NULL,  `course_name` varchar(64) DEFAULT NULL,  PRIMARY KEY (`pid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------  Records of `course`-- ----------------------------BEGIN;INSERT INTO `course` VALUES ('8a8c32c257d67b2a0157d67b2fe90000', 'course1'), ('8a8c32c257d67b2a0157d67b30350001', 'course2'), ('8a8c32c257d67b2a0157d67b30380002', 'course3');COMMIT;-- ------------------------------  Table structure for `stu_cou`-- ----------------------------DROP TABLE IF EXISTS `stu_cou`;CREATE TABLE `stu_cou` (  `stu_id` varchar(32) NOT NULL,  `cou_id` varchar(32) NOT NULL,  PRIMARY KEY (`stu_id`,`cou_id`),  KEY `FK_fd2i9jhyx88ktcbudlprem9y0` (`cou_id`),  CONSTRAINT `FK_fd2i9jhyx88ktcbudlprem9y0` FOREIGN KEY (`cou_id`) REFERENCES `course` (`pid`),  CONSTRAINT `FK_k71umpbvqf7722foi4l5d97g9` FOREIGN KEY (`stu_id`) REFERENCES `student` (`pid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------  Records of `stu_cou`-- ----------------------------BEGIN;INSERT INTO `stu_cou` VALUES ('8a8c32c257d67b2a0157d67bbc5c0003', '8a8c32c257d67b2a0157d67b2fe90000'), ('8a8c32c257d67b2a0157d67bbc5c0003', '8a8c32c257d67b2a0157d67b30350001'), ('8a8c32c257d67b2a0157d67c6f0c0004', '8a8c32c257d67b2a0157d67b30350001'), ('8a8c32c257d67b2a0157d67c6f0c0004', '8a8c32c257d67b2a0157d67b30380002');COMMIT;-- ------------------------------  Table structure for `student`-- ----------------------------DROP TABLE IF EXISTS `student`;CREATE TABLE `student` (  `pid` varchar(32) NOT NULL,  `student_name` varchar(64) DEFAULT NULL,  PRIMARY KEY (`pid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ------------------------------  Records of `student`-- ----------------------------BEGIN;INSERT INTO `student` VALUES ('8a8c32c257d67b2a0157d67bbc5c0003', 'Student1'), ('8a8c32c257d67b2a0157d67c6f0c0004', 'Student2');COMMIT;

代码下载

  CSDN下载
  GitHub下载

0 0