开发者

How to perform atomic operations in Hibernate?

Hi

I have a hibernate entity which has a set of another entity as its field. Something like this:

public class UserEntity implements Srializable {
    private Set<Role> roles;
}

I should keep tables in a way that at least one ADMIN user always be exist in the system. This may be done in a simple way and can be like below:

public void updateUser{
     UserEntity ue = getUser();
   开发者_JAVA技巧  if (userIsNotTheLastAdmin(ue)) {
     /** Here is a race condition **/
         roles.remove(Role.ADMIN);
         getSession().saveOrUpdate(ue);
     }              
}

But the real problem happens when we have concurrent operations. How can I perform all of the operation in an atomic way?

Thanks,

HM


since you probably dont want to lock a whole db table, which is quite an evil thing to do, you could have a field in your group table with a usercount value, then you can span your transactions over user table manipulations and the update of the corresponding field value in the group table and make sure that the usercount for specific groups does not drop below 1. since hibernate acquires write locks for updates automatically you wont have to think about manual locking strategies as described here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/transactions.html#transactions-locking

hope that helped..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜