前提:系统有学校-学生关系,学校能够包含多个学生,学生只能属于一个学校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);