我正在开发 Spring Data JPA Postgres 示例。在这个例子中,我建立了 Student 和 StudentMember 之间的关系。
Student.java
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(name="student_name_key",columnNames = {"studentName"})
})
public class Student{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "studentId")
private Long studentId;
@Column(name = "studentName", nullable = false)
private String studentName;
@OneToMany(mappedBy = "student", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<StudentMember> studentMembers;
}
StudentMember.java
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table
public class StudentMember {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long studentMemberId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="studentId", insertable=false, updatable=false, nullable = false,foreignKey=@ForeignKey(name = "fk_student_id"))
private Student student;
}
MainApp.java
@SpringBootApplication
public class MyProgramApplication implements CommandLineRunner {
@Autowired
ProgramMemberRepository memberRepository;
@Autowired
ProgramRepository programRepository;
public static void main(String[] args) {
SpringApplication.run(MyProgramApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Student student = Student.builder().studentName("John Doe").build();
programRepository.save(student);
StudentMember programMember = StudentMember.builder()
.student(student)
.build();
if(Objects.nonNull(student.getStudentMembers())){
student.getStudentMembers().add(programMember);
}
交互式爱情
相关分类