I have 2 entities
That's first entity
public class Manager {
// ...
@OneToMany(mappedBy = "manager", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
private List<ExpertAndRequest> requests;
// ...
}
Second entity. This is the binding table of the two entities.
@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;
}
So I delete the data from the table
this.managerRepository.delete(manager);
And I get exception:
org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation
What am I doing wrong?
EDIT :
I updated class above.
This is the 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;
}
}
The third entity
public class ParticipantRequest {
// ...
@OneToMany(mappedBy = "request", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
private List<ExpertAndRequest> experts;
// ...
}
Example I took from https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany
As you have a bidirectional relation between the Parent-Entity Manager
and the Child-Entity ExpertAndRequest
what you need is a CascadeType.REMOVE
(or CascadeType.ALL, which includes REMOVE): You say to Hibernate "if the parent entity is removed please remove the child entity too". Take a llo here to understand how to use both CascadeType.REMOVE
and orphanRemoval
尝试使用cascade = {CascadeType.PERSIST, CascadeType.MERGE}
而不是cascade = CascadeType.ALL
并以该站点为参考。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.