Get all updates of Java4s
Follow Us: Email Newsletter

Hibernate Versioning Example, Hibernate Versioning Of Objects

Hibernate » On Jun 13, 2011 { 41 Comments } By Sivateja

Once an object is saved in a database, we can modify that object any number of times right, If we want to know how many no of times that an object is modified then we need to apply this versioning concept.
When ever we use versioning then hibernate inserts version number as zero, when ever object is saved for the first time in the database.  Later hibernate increments that version no by one automatically when ever a modification is done on that particular object.
In order to use this versioning concept, we need the following two changes in our application

  • Add one property of type int in our pojo class
  • In hibernate mapping file, add an element called version soon after id element

Files required to execute this program..

  • (My POJO class)
  • Product.hbm.xml  (Xml mapping file )
  • hibernate.cfg.xml  (Xml configuration file)
  • (java file to write our hibernate logic)




  • In this above mapping file, find the <version> element, there i have given column name as version, actually you can write any name its not predefined.




  • Remember friends, first we must run the logic to save the object then hibernate will inset 0 (Zero) by default in the version column of the database, its very important point in the interview point of view also
  • First save logic to let the hibernate to insert zero in the version column, then any number of update logic’s (programs) we run, hibernate will increments +1 to the previous value
  • But if we run the update logic for the first time, hibernate will not insert zero..! it will try to increment the previous value which is NULL in the database so we will get the exception.

First run the, then only

Eclipse Output

In the database

Guys your know some thing.., actually we can run any logic (Save or Update) :-) for the first time, but make sure the versioning column is a number (>=0), but save logic has ability to insert zero by default if there is no value, and update logic will directly tries to increments already existing value by 1, it wont insert any value by default if its null, hope you are clear about this point, and mates its the very important concept in the interview point of view, if you have any doubt just Ask a Question on this our team will respond ASAP

You Might Also Like

  ♦ About Author ♦

Full Stack( Java/J2EE & UI/UX ) Developer and founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog. Sign-up for the Email Newsletter for your daily dose of Java tutorials.


41 Responses to “Hibernate Versioning Example, Hibernate Versioning Of Objects”
  1. venugopal says:

    hI i am executing the above program as same as your saying.
    but i got these exception.please help me.

    SEVERE: Error parsing XML: hibernate.cfg.xml(7) Element type “session-factory” must be followed by either attribute specifications, “>” or “/>”.
    Exception in thread “main” org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
    at org.hibernate.cfg.Configuration.doConfigure(
    at org.hibernate.cfg.Configuration.configure(
    at org.hibernate.pojo.ClientForSave_1.main(
    Caused by: org.dom4j.DocumentException: Error on line 7 of document : Element type “session-factory” must be followed by either attribute specifications, “>” or “/>”. Nested exception: Element type “session-factory” must be followed by either attribute specifications, “>” or “/>”.
    at org.hibernate.cfg.Configuration.doConfigure(
    … 2 more

  2. Java4s says:


    Seems its the syntax issue, please download the program by clicking download button and try from your end, unlike copy the source from the text [ As some times we may copy other characters ]

    Its working fine from my end.

  3. susil sahoo says:

    Am read about version concept in hibernate. But can u please explain “why this concept comes into picture?”. Is it helpful for threading concept in hibernate ?

    Thanks in Advance.

  4. Java4s says:

    @susil sachoo

    With hibernate versioning we will be able to know, how many times a particular object is modified ( how many time a row got updated ) in the database.

    There is no way relation with threading concept I guess.

  5. Vivek says:

    Hi Java4s,

    Please tell me how to insert date and time when ever the data gets updates in the database instead of how many number of times updated.


  6. Java4s says:


    Add Date and Time just like normal variables, but it will need one more column in the database.

  7. Lavakumar says:


    The PRODUCTS table has PID, PNAME, PRICE and VER columns. what should be the data type of “VER” column.

  8. Java4s says:


    I will tell you how to find the datatype of that column, open SQL prompt and just type ‘desc PRODUCTS‘ and press enter.

    Hope you are seeing it now ;) are you ?

  9. pallavi says:

    in update logic if the default version value in database is NULL then what happens, if we get an exception can you tell me what exception will it raise?

  10. Arun says:

    Can we Use Directly saveOrUpdate(), for initially run the Program.?? When i tried saveOrUpdate() with first Run, “0” is inserted directly and in second Run it was incremented by one. what is the actual use of ( save(), update(),saveOrUpdate())

  11. Sasikumar says:

    at org.hibernate.engine.Versioning.increment(

    what are the Possibilities of this exception?

  12. Vineet Kumar says:

    Can i make default zero value for version, so that what ever the operation is called like save or update, it will not raise the exception.

  13. Hardeep Kaur says:

    Please help me with a similiar kind of explaination for LAZY loading in hibernate.looking for some urgent help.

  14. Kalpana says:

    I have on doubt ..what will happen if we invoke the method saveOrUpdate()
    at first time..

    whether the version column has 0 value or an exception after the saveOrUpdate() method invocation.

    Kindly clarify my Doubt.


  15. KiranV says:

    This concept is also called Optimistic locking in Hibernate.

    If possible, can you please write a post explaining Pesimistic locking concept also?

  16. MMS says:

    There is a spelling mistake {insert] sorry to correct….i hope it is insert but here it is inset

    Remember friends, first we must run the logic to save the object then hibernate will inset 0 (Zero)

  17. Visitor says:

    Your articles are very simple to understand and you gives the process/execution steps that is very useful to understand the flow.

    I appreciate your team’s work!.

  18. Sumathi says:

    Can set default value for version column in the .hbm.xml file?

  19. anu says:

    suppose i had given a value and saved then what is result of version column and if same value is changed by oher user then wht’s the vesion col value?

  20. Saroj Kumar says:

    Presentation of concept is so lucid, eye-catching and cool, that i would love to learn all the concepts as soon as possible.

  21. Ramesh M says:

    This version concept is required when multiple users using our application.Lets say two threads read the data.First thread update the data and then second thread update the data.We lost the changes done by first thread. see this link Ramesh

  22. Prem says:

    Simple way of explaining concepts.
    Like this tutorial site than others.

  23. Girish N says:

    Can you explain one real use-case where we are going to use Hibernate Versioning concept

  24. Dushyant says:

    hi plz clear suppose i was changed in object state than version will come to ‘0’ in database, after that anyother user will come & change the object state again now version auto increment & assing as ‘1’ in database. now i want our record from the database which i was modified with virson id ‘0’ thn how come its possible.

  25. Farhan says:

    I failed to get to your point when you said,
    “But if we run the update logic for the first time, hibernate will not insert zero..! it will try to increment the previous value which is NULL in the database so we will get the exception.”
    How can you update any object which has not been persisted yet?
    Hibernate assumes that the id field starts out null on new objects and is assigned when they are first saved. So, howcome NULL gets saved in the database.
    Could you elaborate?

  26. lokesh says:

    Hi Sivateja Kandula

    How can we add new column to the existing table using hibernate?

  27. anil says:

    I am getting issue in my app. when i am trying two update second time it is throwing exception instead increment by +1.
    Can you pls help me out.

  28. venu says:

    I have a doubt in first level cache concept.

    If you load any object, for second time onwards it will check in first level cache when call load(). suppose some one did deletion on the same object from database side. Is it load() method works fine or any exdception occurs what to do ?

  29. Tirupathaiah says:

    Hi Java4s,

    What is exact use of versioning in hibernate ?
    What is the use of knowing no. of times of object updation ?

  30. Manas says:


    Please see the following steps and tell me where I am wrong,
    1. Search any content
    2. Edit Entity
    3. Save Entity (and re-fetch for maintaining integrity)
    4. Same session again edit entity and save
    5. Gives hibernate version mismatch

    Please help me out

  31. Thanks for providing this web site.Main point in version is if any changes are done in existing data then only the version values is going to be change.
    If you execute with out modifying it version number won’t change.try it

  32. pradeep says:

    if we dont save any table row and we modify it then any change is there

  33. Guru says:

    Thanks for providing this web site. i tried this versioning in my example but getting below exception . please clarify this.
    LF4J: See for further details.
    org.hibernate.MappingException: Unknown entity: versioning.Employee

  34. Santosh says:

    So while creating table in DB (through script) initialized version column to its default (for int 0). Now executing update. So now column is not null this is zero(it default value). Instead of using save() first, executing update() first with all other data for column. what will be the result ?

  35. Heeresh says:

    means we have to create version field in table

  36. Manohar says:

    Hi java4s,

    In my application am using version feature.I am getting some errors

    1)when i am trying to update the record for the first time it got updated and in version column saved with 1.
    2)But second time am updating the same record by using without loading data from db i am getting below error.

    can u explain why am getting error?

    Exception in thread “main” org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.osi.pojo.Employee#1]
    at org.hibernate.persister.entity.AbstractEntityPersister.check(
    at org.hibernate.persister.entity.AbstractEntityPersister.update(
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(
    at org.hibernate.persister.entity.AbstractEntityPersister.update(
    at org.hibernate.action.EntityUpdateAction.execute(
    at org.hibernate.engine.ActionQueue.execute(
    at org.hibernate.engine.ActionQueue.executeActions(
    at org.hibernate.engine.ActionQueue.executeActions(
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(
    at org.hibernate.impl.SessionImpl.flush(
    at org.hibernate.impl.SessionImpl.managedFlush(
    at org.hibernate.transaction.JDBCTransaction.commit(
    at com.osi.test.Test.main(

  37. Rinky Arora says:


    i am using second approach of updating record in database (by creating new object),with version control , but its giving error :

    org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.eric.employee.Employee_Info#4]

    what does this error means , and why am getting this error only when using second approach of updation by creating new object, but with 1st approach ie. loading the object and then updating its executing smoothly.
    Need ur help on this.

  38. Rinky Arora says:


    i am using 2nd approach of updation (creating new object), and with versioning
    its giving error : org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.eric.employee.Employee_Info#4]

    Need ur help.

  39. Sonu says:

    is it possible to see all the update done on a object . I mean suppose 4 update has done on a particular object and I want to see all the update , update 1 ,update 2, ….. . like history.

  40. bala says:

    ERROR: ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired

    Jul 25, 2016 12:52:57 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    INFO: HHH000232: Schema update complete
    Hibernate: select max(product_id) from product
    Hibernate: insert into product (product_name, price, product_id) values (?, ?, ?)

  41. Raunak says:


    I am using the concept of versioning and I am getting a exception like: “Row was updated or deleted”.
    On my investigation I found that If version id of any record is greater than my inserted POJO object than this exception will occur.
    Ex:- In DB employee table one employee version id is 2 and on the time of updating the same employee record my POJO object version id is 1 than its throwing the exception.
    (In DB version id is incremented by some another thread)
    So kindly suggest me some solution to handle version id with multi threading updation.

    Thanks in advance.


By posting your answer, you agree to our comments policy.
What would you like to learn today?
Browse these popular technologies
Hibernate spring struts Servlets ajax Log4j jQuery Json Core Java Web Services AngularJs
Most Recent Tutorials
Hibernate_Logo Hibernate Recent Posts Spring_Logo Spring Recent Posts Struts_Logo Struts Recent Posts
Useful Links Current & UpComing Tutorials
  Web Services [ SOAP ], JSP
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2016 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.