10

I am completely new to Hibernate and Spring and in my attempt to learn Spring, Hibernate, Maven etc I only know how to run a hello world example using all of the three. With my basic understanding I have been assigned a task for performing optimistic locking. As far as I have googled it I can only see it is not very difficult all I need is to add a version tag in my xml and integer variable version in my mapped class.. Like this...

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

my xml should be like this

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

And hibernate will automatically take care of versioning when second user saves, hibernate finds this user is working on the stale data and throws StaleObjectException.

Just wanted to confirm my understanding, thanks in advance.

It will be really helpful if some one can point me to a hello world example for this.

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

2 Answers 2

13

I used Hibernate annotations and here is my implementation of optimistic locking

@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 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 element 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, new element in DB has version 0. After modifying - 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;
    }
}
9
  • hi sergey thanks a lot for replying !!! I want to know that is above code is enough don't I have to include anything in the updates query like update MyObject set data='12.99', OBJ_VERSION=2 where ITEM_ID=123 and OBJ_VERSION=1 ... If yes then how i will manage version in real time i.e. because in real time version=1 or version =2 will not suffice. Do we have to implement based on time stamp Aug 2, 2011 at 11:43
  • Hey Sergey thanks a lot I understood the optimistic locking and with your help i am able to see the change in version in my database. but now the next glitch is to write a test case for it ... I actually want to capture the StaleStateException and would like to warn the user about the dirty update by using a user-friendly query... If we can finish it till the end on this page then many can get help from it.. Aug 2, 2011 at 18:54
  • In my attempt to write test case for above I tried something given in this link but dont know what jar to include and in which jar i can find AbstractTransactionalDataSourceSpringContext...can you please provide me idea to test it... moreover when I run above case for first time then it works fine and value of version increases from 0 to 1 but on running for second time the value of version doesn't increases to 2. do I have to manually reset the value to 0 after each update. Aug 2, 2011 at 21:09
  • Here is algoritm: 1. Open first session first_session = HibernateHelper.getSessionFactory().openSession(); 2. Get the object from db by id and change it's field to another value List<Ent1> list = (List<Ent1>)session.createQuery("FROM Ent1 WHERE a1 = 0").list(); Ent1 ent = list.get(0); ent.setA2(new Integer(1000)); 3. Open second session (like the first one) 4. Get the same object by id, change one of it's fields to another value and save this object. 5. Try to call session.merge on first object and you'll get exception first_session.merge(ent); Aug 3, 2011 at 11:58
  • It is because the object you get from db with first session has version 0 (or another). After you get this object from db with second session, it has version 0 too, but after you save it, object in database will have version 1, and first object (in memory) - version 0. If you try to save object with old value of session, you'll get stale exception. Hope it helps. Aug 3, 2011 at 12:03
1

If we are using the xml style we can use as below in the hbm file:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.