开发者

Hibernate how to delete objects in a set?

开发者 https://www.devze.com 2023-02-07 22:39 出处:网络
I have an object User (has id, username, password) that has a set of UserRoles (has id, username, userrole).

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
use开发者_如何学JAVArname
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


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:

  • 11.11. Transitive persistence
0

精彩评论

暂无评论...
验证码 换一张
取 消