How to make optimistic sleep lock

I am completely new to Hibernate and Spring, and in my attempt to learn Spring, Hibernate, Maven, etc. I only know how to run the greeting example using all three. With my basic understanding, I was entrusted with the task of optimistic blocking. As I understand it, I can only see that it’s not very difficult for me all I need is to add the version tag to my xml and integer variable in my associated class. Like this ...

public class MyClass { ... private int version; ... } 

my xml should look like this

 <class name="MyClass"> <id ...> <version name="version" column="VERSION" access="field"> ... </class> 

And hibernate will automatically take care of version control when saving the second user, hibernate will detect that this user is working with outdated data and throw a StaleObjectException.

Just wanted to confirm my understanding, thanks in advance.

It will be really helpful if someone can give me a welcome example for this.

I would also like to mention that I am trying to implement the "last commit wins" scenerio

+7
source share
2 answers

I used Hibernate annotations and here is my optimistic locking implementation

 @Entity public class MyObject { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String data; @Version private Integer version; // this is version field } 

Here is a working example

 // Entity class with version field @Entity public class Ent1 implements Serializable { private static final long serialVersionUID = -5580880562659281420L; @Id Integer a1; Integer a2; @Version private Integer version; } 

And some code to add one item to DB

  session = HibernateHelper.getSessionFactory().openSession(); transaction = session.beginTransaction(); Ent1 entity = new Ent1(); entity.setA1(new Integer(0)); entity.setA2(new Integer(1)); session.save(entity); transaction.commit(); // get saved object and modify it transaction = session.beginTransaction(); List<Ent1> list = (List<Ent1>)session.createQuery("FROM Ent1 WHERE a1 = 0").list(); Ent1 ent = list.get(0); ent.setA2(new Integer(1000)); session.save(ent); transaction.commit(); 

After creation, the new item in the database has version 0. After the change, version 1.

HibernateHelper.java

 import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateHelper { private static final SessionFactory sessionFactory; static { try { sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } 
+11
source

If we use the xml style, we can use, as shown below, in the hbm file:

 <id name="productId" column="pid" /> **<version name="v" column="ver" />** <property name="proName" column="pname" length="10"/> 
+1
source

All Articles