Java: Hibernate does not see changes in DataBase

百般思念 提交于 2019-12-30 06:25:11

问题


I have two different applications that share the same database. The problem is that when I have an application change something in the database, the other does not update.

I tried to make a session.flush() but it didn't work. The only way is to close the entire session and recreate it, but of course, that takes too long.


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/4313623/java-hibernate-does-not-see-changes-in-database

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