Reputation: 1
I have two entities User and Expense connected by a unidirectional @ManyToMany relation. While trying to delete a User a Referential integrity constraint violation is thrown. What I want to happen if a User gets deleted:
Delete all expenses which have the User in the 'spentBy' field
Do NOT delete expenses, but remove reference, which have the User in the 'spentFor' field. Setting the fields null would be sufficient as well
I know why this happens and what the problem is however even with looking at other StackOverflow articles I have not found one that can solve my problem. Because the User does not have a @ManyToMany field for Expenses, all solutions I found, do not work.
Thanks in advance!
(I removed all Lombok Getters, Setters for readablity)
My entities are:
public class Expense {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private double amount;
@NotNull
private String name;
@NotNull
@OneToOne(fetch = FetchType.EAGER)
private User spentBy;
@OnDelete(action = OnDeleteAction.CASCADE)
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany
private List<User> spentFor;
public class User implements UserDetails {
@SequenceGenerator(
name = "user_sequence",
sequenceName = "user_sequence",
allocationSize = 1
)
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "user_sequence")
@Column(name = "id", nullable = false)
private Long id;
... (no relation to Expense entity!)
detailed Stacktrace (german version, but you might understand what you need to):
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referentielle Integrität verletzt: "FKLECP8QCGQCV5JQGM8FTNMIY0Q: PUBLIC.EXPENSE_SPENT_FOR FOREIGN KEY(SPENT_FOR_ID) REFERENCES PUBLIC.APPLICATION_USER(ID) (CAST(2 AS BIGINT))"
Referential integrity constraint violation: "FKLECP8QCGQCV5JQGM8FTNMIY0Q: PUBLIC.EXPENSE_SPENT_FOR FOREIGN KEY(SPENT_FOR_ID) REFERENCES PUBLIC.APPLICATION_USER(ID) (CAST(2 AS BIGINT))"; SQL statement:
delete from application_user where id=? [23503-214]
I have already tried using the @OnDelete Annotation but this did not change anything. Also the cascade = CascadeType.ALL is not suitable, as I have the case where the child gets deleted and not the parent.
Upvotes: 0
Views: 216
Reputation: 11
In bidirectional mapping, one entity will be unaware of another entity
so in a bidirectional relationship, we mention which entity side will update links between the two tables.
To save/delete the association, save the owner entity of the relation.
Upvotes: 1