Possible hibernate exceptions when two threads update the same Object?

拥有回忆 提交于 2019-12-11 12:50:16

问题


Could someone help me with the possible hibernate exceptions when two threads update the same Object?

ex: employee with name "a", age "30" and address "test" thread1 tries to update "a" to "b" and thread2 tries to update "a" to "c"

Thanks in advance, Kathir


回答1:


If your object is a Hibernate entity, then two threads shouldn't have a reference to the same object in the first place.

Each thread will have its own Hibernate session, and each session will have its own copy of the entity. If you have a field annotated with @Version in your entity, for optimistic locking, one of the thread will get an OptimisticLockException. Otherwise, everything will go fine, and the last thread to commit will win.




回答2:


Thanks for the answers and below are the comments after observation and analysis

  1. We can also do a conditional update with where clause in the query and use executeUpdate() method. Ex: The Hibernate - Query - executeUpdate() method updates and return the number of entities updated. So if the executeUpdate() returns "zero" it means the row has been already updated by another thread. (No Exception)

  2. Using @Version. (OptimisticLockException)

  3. Using Row Level DB lock. (DB Exception)

  4. Using Synchronization. (Java Synchronization Exception)



来源:https://stackoverflow.com/questions/13374322/possible-hibernate-exceptions-when-two-threads-update-the-same-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!