JPA 級聯保存的問題

前提:系統有學校-學生關係,學校能夠包含多個學生,學生只能屬於一個學校mysql

在使用 spring-data-jpa 的時候,保存學校的同時保存學生信息,不須要先逐個保存學生信息,再將學生信息放在學校中保存學校spring

首先spring data jpa 配置須要設置數據庫方言,不然回有外鍵不生效的sql

spring: datasource: url: jdbc:mysql://localhost:3306/iot?serverTimezone=GMT%2B8&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8&useSSL=false driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 jpa: show-sql: true hibernate: ddl-auto: update # 不增長出問題 database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

學校信息:數據庫

@Entity(name = "t_school") @Data @ToString(exclude = "students") public class School { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; 
   //一對多 @OneToMany(fetch
= FetchType.EAGER,mappedBy = "school",cascade = CascadeType.ALL) private List<Student> students = new ArrayList<>(); public void addStudent(Student stu){ if(stu != null){ students.add(stu); } } }

學生信息:app

@Entity(name = "t_student") @Data @ToString(exclude = "school") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; 
  //多對一 @ManyToOne(cascade
= CascadeType.ALL) @JoinColumn(name = "school_id",nullable = false) @JsonIgnore @JsonIgnoreProperties private School school; }

測試、保存學校信息測試

@RestController public class TestController { @Autowired private SchoolRepository schoolRepository; @GetMapping("/save") public void save(){ School school = new School(); school.setName("北京中學"); Student student = new Student(); student.setName("張三");  student.setSchool(school); Student student2 = new Student(); student2.setName("李四");  student2.setSchool(school); school.addStudent(student); school.addStudent(student2); System.out.println(school); schoolRepository.saveAndFlush(school); } }

在新建一方信息,將多方信息保存在一方的集合列表中,若是沒有設置 一方的信息,將致使保存多方抱錯,外鍵id 不能爲 nullfetch

student2.setSchool(school);

最後只須要保存一方信息,便可以將多方的信息一塊兒保存url

schoolRepository.saveAndFlush(school);
相關文章
相關標籤/搜索