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

 

posted @ 2019-09-23 21:05  byebai95  阅读(2349)  评论(1编辑  收藏  举报