nordborg wrote:
This is a quote from the Hibernate documentation at
http://docs.jboss.org/hibernate/stable/ ... tch-directQuote:
This means that manipulating data directly in the database (using the SQL Data Manipulation Language (DML) the statements: INSERT, UPDATE, DELETE) will not affect in-memory state.
So once you start using DML in a transaction the entities in the session cache will no longer match what is in the database. The two examples in your post is the expected behavior. If you, in the first example, want to retrieve the entity with updated values, you can for example call Session.refresh(). I don't know if this method (or an equivalent) exists in EntityManager.
Hi, thanks for answering.
The reason I did an update is that in the particular bit of code I only have the entities id (surrogate key) or code (natural key) - its a soft delete so Im doing "softDeleteById()" which updates an isActive flag for the tuple.
Now, Im actually doing an HQL update, or atleast I guess a JPA update?. I use the entity name rather than the table name. Im NOT using the hibernate session to create the query, only the EntityManager, but Id be surprised if this was the issue. The link you gave goes on to say that using HQL/JP-QL will keep the cache upto date.
Below the commented out stuff is what didnt work (or rather it performed the update but didnt all a subsequent read in the same transaction to read the updated value), and is replace with the entityManager.find followed by an entityManager.merge.
EntityManager entityManager = BaseEntity.entityManager();
// StringBuffer queryBuff = new StringBuffer("UPDATE ");
// queryBuff.append(entityType.trim());
// queryBuff.append(" SET isActive=").append(INACTIVE_STATE);
// queryBuff.append(" WHERE code = :codeparam");
// Query q = entityManager.createQuery(queryBuff.toString());
// q.setParameter("codeparam", entityCode);
BaseEntity entity = findEntityByCode(entityCode, entityType);
try
{
entity.setIsActive(INACTIVE_STATE);
entity.merge();
// q.executeUpdate();
// entityManager.flush();
}
The only thing I can think of is the update is running in a different transaction - or nested transaction, but Im using @Transactional(propagation = Propagation.REQUIRED) throughout (on both service methods and DAO methods for safety - but REQUIRED should propergate the current transaction)