使用CascadeType.ALL的JPA外键约束

时间:2018-05-14 09:57:33

标签: java spring hibernate spring-data-jpa

我有2个实体

这是第一个实体

public class Manager {

    // ...

    @OneToMany(mappedBy = "manager", cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<ExpertAndRequest> requests;

    // ...

}

第二个实体。这是两个实体的绑定表。

@Entity
@Data
@Table(name = "SOME_TABLE_NAME")
@IdClass(ExpertAndRequestId.class)
public class ExpertAndRequest implements Serializable {

    @Id
    private Long managerId;

    @Id
    private Long requestId;


    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "managerId", updatable = false, insertable = false, referencedColumnName = "id")
    private Manager manager;


    @ManyToOne
    @JoinColumn(name = "requestId", updatable = false, insertable = false, referencedColumnName = "id")
    private ParticipantRequest request;



}

所以我从表中删除了数据

this.managerRepository.delete(manager);        

我得到例外:

org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation

我做错了什么?

编辑

我更新了上面的课程。

这是IdClass

@Data
public class ExpertAndRequestId implements Serializable {

    private long managerId;
    private long requestId;


    public int hashCode() {
        return (int)(managerId + requestId);
    }

    public String toString() {

        return String.format("ExpertAndRequestId [expert = \"%s\", request=\"%s\"]", this.managerId, this.requestId);

    }

    public boolean equals(Object object) {
        if (object instanceof ExpertAndRequestId) {
            ExpertAndRequestId otherId = (ExpertAndRequestId) object;
            return (otherId.requestId == this.requestId) && (otherId.managerId == this.managerId);
        }
        return false;
    }

}

第三个实体

public class ParticipantRequest {

    // ...

    @OneToMany(mappedBy = "request", cascade = CascadeType.ALL)
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<ExpertAndRequest> experts;

    // ...

}

示例我从https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany

获取

2 个答案:

答案 0 :(得分:1)

由于您在父实体Manager和子实体ExpertAndRequest之间存在双向关系,因此您需要的是CascadeType.REMOVE(或CascadeType.ALL,其中包括REMOVE):你对Hibernate&#34;如果删除了父实体,请删除子实体&#34;。 点击here了解如何同时使用CascadeType.REMOVEorphanRemoval

答案 1 :(得分:0)

尝试cascade = {CascadeType.PERSIST, CascadeType.MERGE}而不是cascade = CascadeType.ALL并以this site作为参考。