I have two tables
1 | User 1
2 | User 2
user_id | helper_id
1 | 2
The user_id & helper_id are referenced id from users table.
Now, when I delete the user 1, the entry is deleted from Mapping table. But when I delete 2 , i get exception saying, it has been referenced in mapping table
This is my entity code
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "user_helper", joinColumns = {
@JoinColumn(name = "user_id", updatable = false)}, inverseJoinColumns = {
@JoinColumn(name = "helper_id", updatable = false)})
private Set<Users> helpers;
What am I missing
When deleting helper, you must first remove it from any Users that reference it. That will clear the references to it from join table.
user.getHelpers().remove(helper);
session.delete(helper);
I got it working by adding one more mapping line in Users entity as
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "user_helper", joinColumns = {
@JoinColumn(name = "helper_id", updatable = false)}, inverseJoinColumns = {
@JoinColumn(name = "user_id", updatable = false)})
private Set<Users> users;
and before deleting, i clear the users
userEntity.getUsers().clear(); // so, if there are any users associated with helpers, it will be cleared from mapping table
userEntityDAO.delete(userEntity);
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.