gpt4 book ai didi

java - 使用 CascadeType.ALL 的 JPA 外键约束

转载 作者:行者123 更新时间:2023-12-02 11:15:11 24 4
gpt4 key购买 nike

我有 2 个实体

这是第一个实体

public class Manager {

// ...

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

// ...

}

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

@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);        

我得到了异常(exception):

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

我做错了什么?

<小时/>

编辑:

我更新了上面的类(class)。

这是 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 的示例

最佳答案

由于父实体 Manager 和子实体 ExpertAndRequest 之间存在双向关系,因此您需要的是 CascadeType.REMOVE (或 CascadeType.ALL,其中包括 REMOVE):您对 Hibernate 说“如果删除了父实体,请也删除子实体”。拍个照here了解如何使用 CascadeType.REMOVEorphanRemoval

关于java - 使用 CascadeType.ALL 的 JPA 外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50327611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com