如果@ManyToOne双向中的jpa的子表组合键中存在外键,如何停止在父表中插入?

时间:2019-06-26 04:06:07

标签: hibernate spring-boot jpa spring-data-jpa jpa-2.0

我有两个表:   一个是类表,它是父表,另一个是学生表,它是@OneToMany双向映射中的子表:

@Entity
@Table
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
@IdClass(ClassId.class)
public class Class implements Persistable<ClassId> {


    @Id
    private String className;

    @Id
    private String classId;


    @Column
    private String classContent;

    @JsonIgnore
    @OneToMany(mappedBy = "class_fk",cascade = CascadeType.ALL)
    private List<Student> studentList;


    @Override
    public ClassId getId() {

        return new classId//using builder
    }

    @Override
    public boolean isNew() {
        return true;
    }
}

另一个是学生表:

@Entity
@Table
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@IdClass(StudetnId.class)
public class Student implements Persistable<StudetnId> {

    @Id
    @Column
    private String studentName;

    @Id
    @Column
    private String studentGroup;

    @Id
    @ManyToOne
    @JoinColumns ({
            @JoinColumn(
                    name = "className",referencedColumnName = "className"),
            @JoinColumn(
                    name = "classId",referencedColumnName = "classId")
    })
    private Class class_fk;


    @Column
    private String displayName;

    @Column
    private String active;

    @Override
    public StudentId getId() {
        return new StudentId//using builder
    }

    @Override
    public boolean isNew() {
        return true;
    }
}

学生ID类是一个组合键,包含类,studentName和studentGroup,其中类内部的数据(即className和classId)是外键和主键。

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentId implements Serializable {

    private Class class;
    private String studentName;
    private String studentGroup;
}

问题是每当我做studentRepo.save(studentEntity)时,它都会在表即班级表和学生表中插入数据。

要求是,如果我们确实在学生表中插入其外键(即在类表中不存在类名和类ID的学生表),则休眠应抛出错误而不是在两个表中都插入。

Class classOne = Class.builder().className("Sec-B").classID("111").build();
Student student = Student.builder().studentName("Niladri").studentGroup("Science").class_fk(classOne).displayName("ScienceBackground").active("true").build().
studentRepo.save(student);

它首先插入班级,然后插入学生。

0 个答案:

没有答案