I have following entities:
@Entity
@Table(name = "chat",
uniqueConstraints = {
@UniqueConstraint(columnNames = {"user_1", "user_2"})
})
public class Chat {
@ManyToOne
@JoinColumn(name = "user_1")
@OnDelete(action = OnDeleteAction.CASCADE)
private User user1;
@ManyToOne
@JoinColumn(name = "user_2")
@OnDelete(action = OnDeleteAction.CASCADE)
private User user2;
}
User class:
@Entity
@Table(name="users",
uniqueConstraints={
@UniqueConstraint(columnNames={"company_id", "username"})
}
)
public class User {
@Id
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen",strategy=GenerationType.IDENTITY)
private String id;
// there is no field/reference to Chat entity
}
And User entity without any references to Chat entity. I need to remove user with it's chats. Problem is that user id (that I want to remove) could be either in user1
or user2
field. For example, I have user A and user B. They have chat C. And if I try to remove, for example, user A, it should remove user A and chat C. But with provided configuration, I have following error:
Cannot delete or update a parent row: a foreign key constraint fails
(`mydb`.`chat`, CONSTRAINT `FKqslncg7pcc89gvjjpp9jypbha`
FOREIGN KEY (`user_2`) REFERENCES `users` (`id`))
As possible solution I used this answer. But using of
entityManager.remove(user);
entityManager.clear();
does not help. Also, I checked ddl code and there is no any mention of Cascade actions. How to fix this?