I don't know if someone had the same problems that I do..
Here is situation:
1. Let's say I have entity called Account defined in hbm.xml file with following mapping:
<hibernate-mapping>
<class name="com.myhost.objects.Account" table="account_table">
<id name="id" type="int" unsaved-value="null">
<column name="id" not-null="true"/>
<generator class="native"/>
</id>
<property name="amount" type="int">
<column name="amount"/>
</property>
</class>
</hibernate-mapping>
2. Let's say I have multiple java threads which try to lock the same Account object, increase amount by 1000 and flush changes to database.
Here is java code:
Account account = (Account) session.get(Account.class, new Integer(123), LockMode.UPGRADE);
account.setAmount(account.getAmount() + 1000);
session.update(account);
session.flush();
3. After first execution The above java code causes the following queries to the database:
select id, amount from account where id = ? for update;
update account set amount=? where id=?
and it works fine.
ATTENTION.
After second execution from the same thread The above java code causes the following queries to the database:
select id from account where id = ? for update;
update account set amount=? where id=?
Please note, that the field amount is disappeared from select statement.
It means that java code try to lock object in the database and reads all attributes from cache which is not acceptable because some other threads are trying to do the same updates to the object Account, which causes some data loses.
QUESTION:
How to force hibernate always load and lock most recent state of object with given id?
How to force hibernate basically load all object fields with LockMode.UPGRADE and bypass any caches.
BTW. I had impression that LockMode.UPGRADE is pessimistic upgrade lock which bypasses all chaches, but reality is somewhat different.
P.S.My english is not 100%, I know that and I'm sorry.
|