引起:org.postgresql.util.PSQLException:错误:

我正在开发 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);

        }


拉风的咖菲猫
浏览 339回答 1
1回答

交互式爱情

您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先检查这个。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java