user550738
user550738

Reputation:

Hibernate how to delete objects in a set?

I have an object User (has id, username, password) that has a set of UserRoles (has id, username, userrole).

The way things are mapped, the UserRole table looks like this:

USER_ROLE
id
username
userrole
userid

When a user gets a higher role, say from "general" to "admin", replace the set of role with a new set of roles like so:

User u = userService.findById(userId);
Set<UserRole> roles = new HashSet<UserRole>();
roles.set(new UserRole(u.getUsername(), "ADMIN");
userService.update(u);

In the end I want there to be one role for the user, but there's two in the database. One "GENERAL" with userId = null, and one "ADMIN" with the correct userId.

Any idea what I need to do so the first role gets deleted instead of having userId set to null?

Need help, thanks! rob

Upvotes: 0

Views: 4752

Answers (1)

axtavt
axtavt

Reputation: 242786

If you want these roles to be deleted from the database when they are removed from the collection, you need to map the collection with orphanRemoval = true (for JPA 2.0 annotations) or with DELETE_ORPHAN cascading option (for XML or pre-3.5 versions of Hibernate).

Though in that case you can't simply replace the collection, you need to clear the existing collection with its methods, such as clear().

See also:

Upvotes: 2

Related Questions