Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
     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

like image 995
Hamzeh Avatar asked Nov 14 '22 23:11

Hamzeh


1 Answers

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..

like image 103
fasseg Avatar answered Jan 28 '23 11:01

fasseg