0

I'm new to hibernate and trying to solve a mystery around our application which heavily uses hibernate to persist data in MySQL.

I see that sometimes properties not set with the expected values in DB.

After some analysis, I see that when DBCommit thread is committing the transaction, at the same time application thread is also updating the same object which committer thread is trying to commit and in that race, update is not reflecting the same values in DB as expected.

So my question: Is it a good practice to share the same object with in the application code and persistence layer or should the application thread always create a deep copy of the object and then hand over the object to DB Committer thread.

Just to elaborate more on this, consider the below: Application receives one event E1 and as this is the first event we create one object called R1, application thread sets all the field values for R1 and then send it to DBManager. This DBManager on receiving this R1, puts into a batch array and return the call to application. Application now put the object R1 to it's application cache.

Now when the batch threads takes the object from batch array, it does the following: - Retrieve the session - Begin the transaction - save the object to the transaction using saveOrUpdate - then commit the transaction.

Now while batch thread committing the transaction, application thread receives another event E2, which retrieves the object R1 from the application cache and start updating few fields.

After the transaction is committed, I see the few values are not correct.

Then the same process is repeated for this update and DB saveOrUpdate is done and then commit. Though still the values are not correct.

I want to know in this above scenario, can hibernate udpate the R1 object with some old values which can overwrite the values updated by application thread.

Please suggest.

  • 1
    Possible duplicate of [Hibernate session thread safety](http://stackoverflow.com/questions/20150110/hibernate-session-thread-safety) – Erwin Bolwidt Mar 14 '17 at 10:59
  • It is not the duplicate of http://stackoverflow.com/questions/20150110/hibernate-session-thread-safety – ANewDeveloper Mar 14 '17 at 11:11
  • Don't describe your code. Post it. You're really looking for trouble if, instead of saving the object when the user presses "Save", you just give it to another thread to save it later. Just don't do that. Using an "application cache" is also looking for trouble. Just get the data from the database. – JB Nizet Mar 15 '17 at 06:29

0 Answers0