Spring 多对多
Posted hzyhx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring 多对多相关的知识,希望对你有一定的参考价值。
多对多特点:建表只建了两个,但再数据库里就会产生三张表
第一步:创建一个Spring Starter Project工程
注意:这里创建和以前创建Spring Starter Project工程一样,但要添加驱动不一样,这里只添加了Spring Boot DevTools和 Spring Data JPA驱动
第二步:添加配置文件
(1)pom.xml的添加以下代码
1 <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
添加位置,如下图
再在pom.xml中的<dependencies>标签中添加以下代码
1 <dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4 <version>5.1.38</version> 5 </dependency>
添加位置如下图
(2)配置此文件application.properties 添加以下代码
1 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 2 spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=UTF-8//将testdb改成自己的数据库名 3 spring.datasource.username=testdb //自己的数据库名 4 spring.datasource.password=testdb //自己的数据库密码 5 6 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect 7 spring.jpa.hibernate.ddl-auto = update//自动创建表 8 9 logging.level.org.hibernate.SQL=DEBUG 10 logging.level.org.hibernate.type=TRACE
注意:连接数据库的时候,记得连自己的
(3)在/src/main/java中的配置(config)包,添加扫描包 ,添加以下代码
1 //Spring Boot应用 2 @SpringBootApplication 3 //@EnableJpaRepositories启用JPA存储库 4 @EnableJpaRepositories(basePackages = "com.hzy.dao") 5 //@EntityScan实体扫描 6 @EntityScan(basePackages = "com.hzy.entity")
注意:要扫描的包写成自己的包名。
假如:你的dao包名叫:com.xxx.dao;你的实体包叫:com.xxx.entity,
则你应该将com.hzy.dao改成com.xxx.dao;com.hzy.entity改成com.xxx.entity
第三步:再/src/main/java目录下建一个dao包和一个实体(entity)包,如图
第四步:在实体包中建一个Student实体类和一个Course实体类
多对多重要代码:
1 //@ManyToMany多对多 2 //cascade = CascadeType.ALL 级联关系=拥有以上所有级联操作权限 3 @ManyToMany(cascade = CascadeType.ALL) 4 5 /** 6 *@JoinTable 关联表 * 7 *name = "student_has_course" 关联表名 8 *joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id") 维护端外键 9 *inverseJoinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id") 被维护端外键 */ 10 @JoinTable(name = "student_has_course", joinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id"))
Student实体类,代码如下:
1 package com.hzy.entity; 2 3 import java.io.Serializable; 4 import java.util.Set; 5 6 import javax.persistence.CascadeType; 7 import javax.persistence.Entity; 8 import javax.persistence.GeneratedValue; 9 import javax.persistence.GenerationType; 10 import javax.persistence.Id; 11 import javax.persistence.JoinTable; 12 import javax.persistence.ManyToMany; 13 import javax.persistence.Table; 14 import javax.persistence.JoinColumn; 15 16 @Entity//实体 17 @Table(name="student")/**@Table表 (name="student")数据库里的表名*/ 18 public class Student implements Serializable 19 20 private static final long serialVersionUID = 5464805301818181901L; 21 22 @Id 23 @GeneratedValue(strategy=GenerationType.IDENTITY) 24 private int id; 25 26 private String name; 27 28 //@ManyToMany多对多 29 //cascade = CascadeType.ALL 级联关系=拥有以上所有级联操作权限 30 @ManyToMany(cascade = CascadeType.ALL) 31 32 /** 33 *@JoinTable 关联表 * 34 *name = "student_has_course" 关联表名 35 *joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id") 维护端外键 36 *inverseJoinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id") 被维护端外键 */ 37 @JoinTable(name = "student_has_course", joinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id")) 38 39 //这里表示一个学生可以有多门课程,知识用到了集合Set<T> 40 private Set<Course> course; 41 42 public Student() 43 44 45 46 public Student(String name) 47 super(); 48 this.name=name; 49 50 51 public int getId() 52 return id; 53 54 55 public void setId(int id) 56 this.id = id; 57 58 59 public String getName() 60 return name; 61 62 63 public void setName(String name) 64 this.name = name; 65 66 67 public Set<Course> getCourse() 68 return course; 69 70 71 public void setCourse(Set<Course> course) 72 this.course = course; 73 74 75 @Override 76 public String toString() 77 return "Student [id=" + id + ", name=" + name + ",course="+ course +"]"; 78 79 80 81 82
Course实体类,代码如下:
1 package com.hzy.entity; 2 3 import java.io.Serializable; 4 import java.util.Set; 5 6 import javax.persistence.CascadeType; 7 import javax.persistence.Entity; 8 import javax.persistence.GeneratedValue; 9 import javax.persistence.GenerationType; 10 import javax.persistence.Id; 11 import javax.persistence.JoinTable; 12 import javax.persistence.ManyToMany; 13 import javax.persistence.Table; 14 import javax.persistence.JoinColumn; 15 16 @Entity//实体 17 @Table(name = "course")//@Table添加表 name = "course"表名 18 public class Course implements Serializable 19 20 private static final long serialVersionUID = -35542463820821380L; 21 22 23 @Id 24 @GeneratedValue(strategy = GenerationType.IDENTITY) 25 private int id; 26 27 private String name; 28 29 //@ManyToMany多对多 30 //cascade = CascadeType.ALL 级联关系=拥有以上所有级联操作权限 31 @ManyToMany(cascade = CascadeType.ALL) 32 33 /** 34 *@JoinTable 关联表 * 35 *name = "student_has_course" 关联表名 36 *joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id") 维护端外键 37 *inverseJoinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id") 被维护端外键 */ 38 @JoinTable(name = "student_has_course", joinColumns = @JoinColumn(name = "course_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "student_id", referencedColumnName = "id")) 39 40 //这里表示一个学生可以有多门课程,知识用到了集合Set<T> 41 private Set<Student> student; 42 43 public Course() 44 45 46 public Course(String name) 47 super(); 48 this.name = name; 49 50 51 public int getId() 52 return id; 53 54 55 public void setId(int id) 56 this.id = id; 57 58 59 public String getName() 60 return name; 61 62 63 public void setName(String name) 64 this.name = name; 65 66 67 public Set<Student> getStudent() 68 return student; 69 70 71 public void setStudent(Set<Student> student) 72 this.student = student; 73 74 75 @Override 76 public String toString() 77 return "Course [id=" + id + ", name=" + name + ", student=" + student + "]"; 78 79 80 81 82
第五步:在dao包中建一个StudentRepository和CourseRepository类
StudentRepository类,代码如下:
1 package com.hzy.dao; 2 3 import org.springframework.data.jpa.repository.JpaRepository; 4 import org.springframework.stereotype.Repository; 5 6 import com.hzy.entity.Student; 7 8 @Repository 9 public interface StudentRepository extends JpaRepository<Student, Integer> 10 11
CourseRepository类,代码如下:
1 package com.hzy.dao; 2 3 import org.springframework.data.jpa.repository.JpaRepository; 4 import org.springframework.stereotype.Repository; 5 6 import com.hzy.entity.Course; 7 8 9 @Repository 10 public interface CourseRepository extends JpaRepository<Course, Integer> 11 12 13
第六步:在config配置文件中 进行实例化student和course实体类
完整的config配置文件代码,如下:
1 package com.hzy.config; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.boot.CommandLineRunner; 8 import org.springframework.boot.SpringApplication; 9 import org.springframework.boot.autoconfigure.SpringBootApplication; 10 import org.springframework.boot.autoconfigure.domain.EntityScan; 11 import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 12 13 import com.hzy.dao.CourseRepository; 14 import com.hzy.dao.StudentRepository; 15 import com.hzy.entity.Course; 16 import com.hzy.entity.Student; 17 18 @SpringBootApplication 19 @EnableJpaRepositories(basePackages = "com.hzy.dao") 20 @EntityScan(basePackages = "com.hzy.entity") 21 public class HibernateManyToManyMappingApplication implements CommandLineRunner 22 23 @Autowired 24 private StudentRepository studentRepository; 25 26 27 @Autowired 28 private CourseRepository courseRepository; 29 30 public static void main(String[] args) 31 SpringApplication.run(HibernateManyToManyMappingApplication.class, args); 32 33 34 @Override 35 public void run(String... args) throws Exception 36 37 Student JackSon = new Student("易烊千玺"); 38 Student wy = new Student("王源"); 39 40 Course dance = new Course("跳舞"); 41 Course sing = new Course("跳舞"); 42 Course perform = new Course("跳舞"); 43 44 //将所有的功课放到set<>集合中 45 Set<Course> sets = new HashSet<>(); 46 //将跳舞、跳舞、跳舞添加到集合里 47 sets.add(dance); 48 sets.add(sing); 49 sets.add(perform); 50 51 //再用JackSon学生调用刚放到集合里的功课 52 JackSon.setCourse(sets); 53 54 Set<Course> sets2 = new HashSet<>(); 55 sets2.add(dance); 56 sets2.add(sing); 57 58 wy.setCourse(sets2); 59 60 //再将JackSon学和JackSon的功课保存到StudentRepository中 61 studentRepository.save(JackSon); 62 63 64
第七步:运行
以上是关于Spring 多对多的主要内容,如果未能解决你的问题,请参考以下文章