tags:

views:

970

answers:

3

I am new to hibernate just to mention but I know that it has optimistic locking support. I was searching all day and I wasn't able to find tutorial how to implement it in some basic application.

So fore example I have this mysql table http://pastebin.com/m574200ce and I have this hibernate mapping file: http://pastebin.com/m2047dd98 (generated with NetBeans 6.5). What else do I need to add to this file to make optimistic locking which works on this simple table when I do (for example):

session.saveOrUpdate(user);
tx.commit();
+4  A: 

Optimistic Locking is achieved using the version capability of hibernate. Read through the doc below to see how it is used.

http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping.html#mapping-declaration-version

caskey
+2  A: 

If you are using JPA (annotation style) you can add a column

@Version
private Long version;

If you turn on sql level debugging for hibernate, you'll see that each update/delete statement will be extended by

WHERE ... and alias.version=?

Which allows Hibernate change only rows with the same value in version column that must be equal to version's value of loaded java object (i.e. optimistic locking). If the version doesn't match to each other StaleObjectStateException will be thrown.

FoxyBOA
A: 

define field in your pojo

private long version;

and in hibernate mapping like

done version property is automatically managed by Hibernate

Inderjeet Singh