Java: Hibernate does not see changes in DataBase

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.


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.

    链接地址: http://www.djcxy.com/p/3882.html

    上一篇: 生成综合社交网络?

    下一篇: Java:Hibernate在DataBase中看不到变化