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.
saveOrUpdate() Hibernate will check if the object is transient (it has no identifier property) and if so it will make it persistent by generating it the identifier and assigning it to session. If the object has an identifier already it will perform . update() .
save Save method stores an object into the database. That means it insert an entry if the identifier doesn't exist, else it will throw error. If the primary key already present in the table, it cannot be inserted. update Update method in the hibernate is used for updating the object using identifier.
How to Save Data? Hibernate provides different methods to save data into the database: save(): It returns a generated identifier and throws an exception when an entity is already available in the database. persist (): It returns a void and throws an exception when an entity is already available in the database.
Hibernate persist is similar to save (with transaction) and it adds the entity object to the persistent context, so any further changes are tracked. If the object properties are changed before the transaction is committed or session is flushed, it will also be saved into database.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With