NikolayGS
NikolayGS

Reputation: 290

Hibernate transaction problem

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

Answers (2)

Zulfi
Zulfi

Reputation: 586

In hibernate either you are using JPA API or Hibernate's native API any query that you run using below interface

  1. Criteria (Hibernate Native API)
  2. Query (Hibernate Native API)
  3. EntityManager createQuery() (JPA)

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-

https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#refresh%28java.lang.Object%29

Otherwise as a convention always run your DML before loading any data in the persistence context.

Hope this helps :D

Upvotes: 0

Tzvetan Mikov
Tzvetan Mikov

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

Related Questions