Reputation: 290
When I execute some queries inside Hibernate transaction -> the data successfully updated in my mysql, but in my application there are still old values. When i restart - it`s Ok. If i set autocommit mode - works fine, but i have to use transaction ;-). Any ideas? Thanks in advance.
Upvotes: 0
Views: 529
Reputation: 586
In hibernate
either you are using JPA API
or Hibernate's native API any query that you run using below interface
The queries dont interact with the second level or first level cache . They directly hit the database .If your query is updating the entities currently in the persistence context , those entities will not reflect the changes.This is the default behavior.
In order to update your context to show the latest state of entity use the refresh() in Session or in EntityManager to reflect the latest entity state in persistence context. Read the docs below for more info
http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#refresh-java.lang.Object-
Otherwise as a convention always run your DML
before loading any data in the persistence context.
Hope this helps :D
Upvotes: 0
Reputation: 511
Manipulating the database directly with UPDATE doesn't affect the objects cached in the session. You should clear the session (Session.clear()). Something like:
session.flush()
session.clear()
query.executeUpdate()
Or even better, you can avoid the problem by not using update queries and manipulating the object state in memory:
myobj.setName(newValue)
session.saveOrUpdate(myobj)
Upvotes: 1