Java: Hibernate does not see changes in DataBase

核能气质少年 提交于 2019-11-30 20:05:05

Short answer: issue a session.refresh(obj) every time you want to display some object. It will force Hibernate to go to the database. Another solution is to use a StatelessSession, which won't cache anything (not even 1st level cache), forcing your applications to go the database every time a record is needed:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-statelesssession

But of course, if that's too much, then you can consider using some sort of locking (pessimistic or optimistic):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/transactions.html#transactions-optimistic

But really, if you have two different concurrent systems using the same record, there's nothing that Hibernate can solve by itself. It is something that you should consider in the architecture of your systems.

If I understand correctly this is what happens in your scenario:

  • app1 starts a transaction
  • app2 (starts and) commits another transaction
  • app1 expects to be able to read the changes done by app2

If this is the case you need to check out your database Isolation levels.

Or you could of course start a new transaction when you want to read updated data. Check out the Hibernate transactions documentation

I haven't tested this but the Session class has a clear method that evicts all loaded entities. This should force a reload from the db.

For me it works to commit the current transaction and begin a new one after the other application has applied its modifications.

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