JPA 級聯保存的問題


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

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

首先spring data jpa 配置需要設置數據庫方言,否則回有外鍵不生效的

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); } } }

學生信息:

@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 不能為 null

       student2.setSchool(school);

最后只需要保存一方信息,即可以將多方的信息一起保存

schoolRepository.saveAndFlush(school);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM