我正在开发 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@Tablepublic 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@SpringBootApplicationpublic 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); }
1 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
您Student在实体中的关系StudentMember是只读的。
消除insertable=false, updatable=false
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="studentId", nullable = false,foreignKey=@ForeignKey(name = "fk_student_id"))
private Student student;
否则 Hibernate 不写入外键。
另外我不确定你的映射是否正确。PostgreSQL 抱怨一个列被调用student_id但名称@JoinColum是studentId
先检查这个。
添加回答
举报
0/150
提交
取消