I am using hibernate with JPA annotations for relationship mapping.
I have three entities in my code User
Group
& User_Group
User
& Group
are in a ManyToMany
relationship.
User_Group
is a kinda bridge table but with some additional fields. So here is the modified mapping code.
User
@Entity
@Table(name = "USERS")
public class User {
@OneToMany(mappedBy = "user")
private Set<UserGroup> userGroups
}
Group
@Entity
@Table(name = "GROUPS")
public class Group {
@OneToMany(mappedBy = "group")
private Set<UserGroup> userGroups
}
UserGroup
@Entity
@Table(name = "USERS_GROUPS")
public class UserGroup {
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "GROUP_ID")
private Group group;
}
When I set the user & group object to the usergroup & save it.
User user = new User("tommy", "ymmot", "[email protected]");
Group group = new Group("Coders");
UserGroup userGroup = new UserGroup();
userGroup.setGroup(group);
userGroup.setUser(user);
userGroup.setActivated(true);
userGroup.setRegisteredDate(new Date());
session.save(userGroup);
Things work fine. With CascadeType.ALL
the group object & user object are updated too. But when I delete the userGroup object. The child object are deleted too.
Deletion of child objects is a strict no no.
There is no CascadeType.SAVE-UPDATE
in JPA, which just does save or update but no delete. How do I achieve this.
If I remove the CascadeType.ALL
from the mapping the child objects don't get updated & I need them to be updated.
SAVE_UPDATE is for save(), update(), and saveOrUpdate(), which are 3 Hibernate-proprietary methods. JPA only has persist()
and merge()
. So, if you want to use cascading on Hibernate-proprietary methods, you'll need to use Hibernate-proprietary annotations. In this case, Cascade.
Or you could stop using the Hibernate Session, and use the standard JPA API instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With