Newsletter |
Hibernate Versioning Example, Hibernate Versioning Of Objects
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..
- Product.java (My POJO class)
- Product.hbm.xml (Xml mapping file )
- hibernate.cfg.xml (Xml configuration file)
- ClientForSave_1.java (java file to write our hibernate logic)
- ClientForUpdate_2.java
Product.java
package str; public class Product{ private int productId; private String proName; private double price; private int v; public void setProductId(int productId) { this.productId = productId; } public int getProductId() { return productId; } public void setProName(String proName) { this.proName = proName; } public String getProName() { return proName; } public void setPrice(double price) { this.price = price; } public double getPrice() { return price; } public void setV(int v) { this.v = v; } public int getV() { return v; } }
Product.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="str.Product" table="products"> <id name="productId" column="pid" /> <version name="v" column="ver" /> <property name="proName" column="pname" length="10"/> <property name="price"/> </class> </hibernate-mapping>
Note:
- 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.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver </property> <property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</property> <property name="connection.username">system</property> <property name="connection.password">admin</property> <property name="dialect">org.hibernate.dialect.OracleDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="Product.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
ClientForSave_1.java
package str; import org.hibernate.*; import org.hibernate.cfg.*; public class ClientForSave_1 { public static void main(String[] args) { Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Product p=new Product(); p.setProductId(104); p.setProName("AC"); p.setPrice(14000); Transaction tx = session.beginTransaction(); session.save(p); System.out.println("Object saved successfully.....!!"); tx.commit(); session.close(); factory.close(); } }
Note:
- 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.
ClientForUpdate_2.java
package str; import org.hibernate.*; import org.hibernate.cfg.*; public class ClientForUpdate_2 { public static void main(String[] args) { Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); Object o=session.load(Product.class,new Integer(104)); Product s=(Product)o; Transaction tx = session.beginTransaction(); s.setPrice(4000); // implicitly update method will be call tx.commit(); System.out.println("Object Updated successfully.....!!"); session.close(); factory.close(); } }
First run the ClientForSave_1.java, then only ClientForUpdate_2.java
&
Eclipse Output
In the database
Note(Important..!!!)______
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 the Author .:: | ||
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(Configuration.java:1494)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
at org.hibernate.pojo.ClientForSave_1.main(ClientForSave_1.java:15)
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.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1484)
… 2 more
@venugopal
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.
Hi,
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.
@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.
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.
Thanks
@Vivek
Add Date and Time just like normal variables, but it will need one more column in the database.
Hi,
The PRODUCTS table has PID, PNAME, PRICE and VER columns. what should be the data type of “VER” column.
@Lavakumar
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 ?
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?
if you use update first then you will face these Exception
May 09, 2017 1:47:57 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.1.3
May 09, 2017 1:47:57 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
May 09, 2017 1:47:57 PM org.hibernate.cfg.Environment <clinit>
INFO: using CGLIB reflection optimizer
May 09, 2017 1:47:57 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
May 09, 2017 1:47:57 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: com/configuration/hibernate.cfg.xml
May 09, 2017 1:47:57 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: com/configuration/hibernate.cfg.xml
May 09, 2017 1:47:58 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource: com/mapping/Employee.hbm.xml
May 09, 2017 1:47:58 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.Bean.EUser -> Emp_10
May 09, 2017 1:47:58 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
May 09, 2017 1:47:58 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
May 09, 2017 1:47:58 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 5
May 09, 2017 1:47:58 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
May 09, 2017 1:47:58 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: org.postgresql.Driver at URL: jdbc:postgresql://localhost:5432/Practice
May 09, 2017 1:47:58 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=postgres, password=****}
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: PostgreSQL, version: 9.3.5
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: PostgreSQL Native Driver, version: PostgreSQL 8.3 JDBC4 with SSL (build 603)
May 09, 2017 1:47:59 PM org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.PostgreSQLDialect
May 09, 2017 1:47:59 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
May 09, 2017 1:47:59 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
May 09, 2017 1:47:59 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory createCacheProvider
INFO: Cache provider: org.hibernate.cache.EhCacheProvider
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
May 09, 2017 1:47:59 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
May 09, 2017 1:47:59 PM org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
May 09, 2017 1:47:59 PM net.sf.ehcache.config.Configurator configure
WARNING: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/E:/java%20software/eclipse%20Airsolwin/hibernat%20Basic/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
May 09, 2017 1:47:59 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
May 09, 2017 1:47:59 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: Running hbm2ddl schema update
May 09, 2017 1:47:59 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: fetching database metadata
May 09, 2017 1:47:59 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: updating schema
May 09, 2017 1:48:00 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: table found: public.emp_10
May 09, 2017 1:48:00 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: columns: [password, address, user_id, name, version_id, email]
May 09, 2017 1:48:00 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: foreign keys: []
May 09, 2017 1:48:00 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: indexes: [emp_10_pkey]
May 09, 2017 1:48:00 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: schema update complete
Hibernate: select euser0_.user_id as user1_0_0_, euser0_.version_id as version2_0_0_, euser0_.name as name0_0_, euser0_.password as password0_0_, euser0_.email as email0_0_, euser0_.address as address0_0_ from Emp_10 euser0_ where euser0_.user_id=?
May 09, 2017 1:48:00 PM org.hibernate.event.def.DefaultLoadEventListener onLoad
INFO: Error performing load command
org.hibernate.PropertyAccessException: exception setting property value with CGLIB (set hibernate.cglib.use_reflection_optimizer=false for more info) setter of com.Bean.EUser.setVersion
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValuesWithOptimizer(PojoEntityTuplizer.java:215)
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:185)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:3232)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:129)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:842)
at org.hibernate.loader.Loader.doQuery(Loader.java:717)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:82)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:820)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:62)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:98)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:158)
at com.Bean.EUser$$EnhancerByCGLIB$$14e43df.setName(<generated>)
at com.client.ClientUpdate.main(ClientUpdate.java:20)
Caused by: net.sf.cglib.beans.BulkBeanException
at com.Bean.EUser$$BulkBeanByCGLIB$$d863c8e9.setPropertyValues(<generated>)
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValuesWithOptimizer(PojoEntityTuplizer.java:212)
… 21 more
Caused by: java.lang.NullPointerException
… 23 more
Exception in thread "main" org.hibernate.PropertyAccessException: exception setting property value with CGLIB (set hibernate.cglib.use_reflection_optimizer=false for more info) setter of com.Bean.EUser.setVersion
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValuesWithOptimizer(PojoEntityTuplizer.java:215)
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:185)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:3232)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:129)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:842)
at org.hibernate.loader.Loader.doQuery(Loader.java:717)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:82)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:820)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:62)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:98)
at org.hibernate.proxy.CGLIBLazyInitializer.intercept(CGLIBLazyInitializer.java:158)
at com.Bean.EUser$$EnhancerByCGLIB$$14e43df.setName(<generated>)
at com.client.ClientUpdate.main(ClientUpdate.java:20)
Caused by: net.sf.cglib.beans.BulkBeanException
at com.Bean.EUser$$BulkBeanByCGLIB$$d863c8e9.setPropertyValues(<generated>)
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValuesWithOptimizer(PojoEntityTuplizer.java:212)
… 21 more
Caused by: java.lang.NullPointerException
… 23 more
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())
java.lang.NullPointerException
at org.hibernate.type.IntegerType.next(IntegerType.java:82)
at org.hibernate.engine.Versioning.increment(Versioning.java:131)
what are the Possibilities of this exception?
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.
Hi,
Please help me with a similiar kind of explaination for LAZY loading in hibernate.looking for some urgent help.
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.
Thanks.
This concept is also called Optimistic locking in Hibernate.
If possible, can you please write a post explaining Pesimistic locking concept also?
Hi,
There is a spelling mistake {insert] sorry to correct….i hope it is insert but here it is inset
Note:
Remember friends, first we must run the logic to save the object then hibernate will inset 0 (Zero)
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!.
Can set default value for version column in the .hbm.xml file?
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?
Presentation of concept is so lucid, eye-catching and cool, that i would love to learn all the concepts as soon as possible.
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 http://stackoverflow.com/questions/7631280/hibernate-automatic-versioning Ramesh
Simple way of explaining concepts.
Like this tutorial site than others.
Thanks java4s.com
Can you explain one real use-case where we are going to use Hibernate Versioning concept
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.
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?
Hi Sivateja Kandula
How can we add new column to the existing table using hibernate?
Hi,
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.
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 ?
Hi Java4s,
What is exact use of versioning in hibernate ?
What is the use of knowing no. of times of object updation ?
Hi,
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
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
if we dont save any table row and we modify it then any change is there
Thanks for providing this web site. i tried this versioning in my example but getting below exception . please clarify this.
LF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
org.hibernate.MappingException: Unknown entity: versioning.Employee
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 ?
means we have to create version field in table
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(AbstractEntityPersister.java:1950)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2595)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2495)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2822)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at com.osi.test.Test.main(Test.java:30)
Hi,
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.
Hi,
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.
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.
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
org.hibernate.internal.SessionFactoryImpl@657fa52d
Hibernate: select max(product_id) from product
Hibernate: insert into product (product_name, price, product_id) values (?, ?, ?)
Hi,
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.
Raunak
Hello,
Thanks for providing this web site.
Thanks
A very nice explanation. I always look into this website. I am becoming fan for your explanation. Thanks for providing this site.Doing great job.
Hi, I'm getting this error while running this code.Please help me with this issue
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1526)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1505)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at ClientForSave.main(ClientForSave.java:10)
In hibernates if we try to load an object which is not created yet.then what will happen? whether it creates a object?
How to configure version using annotation
what happens if i use saveorupdate() for existing record
Hi java4s,
What will happen if we update the record which are already exist in db but their version column is empty. Do we need to load those objects and save them so that 0 will be inserted and then update?
how to acheive hibernate versioning using annotations
Could you please provide some solution on below: it's urgent…Bro…req to joining
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.journaldev.spring.model.Person#1]