Reputation: 9
As far as I've experienced JPA/hibernate will return entities that either exists at the database or have been persisted during the transaction and then flushed to the database.
I'd like to be able for certain queries to ask Hibernate for the database as-is without taking into consideration any active transaction, any entity flushed, etc.. In these certain cases I only want to read what it is committed.
Setting the flushmode to 'COMMIT' it is not what I'm looking for as I only want to read DB as is -skipping flushed entities- in certain cases like calling this 'findCommittedEntities' method.
A simple code that shows what I'm looking for:
@Transactional()
public void mySampler(){
Entity ent=new Entity();
entityManager.persist(ent)
/*Here JPA/Hibernate configured with flushmode AUTO will flush the
*persisted entity to db. That's Perfect!
*/
List<Entity> entities=service.findEntities()
//So this list should be of size 1 assuming we started with an empty DB of course!
System.out.println(entities.size())
//But I also would like to be able to read the DB as is:
List<Entity> entitiesCommited=service.findCommittedEntities(...)
//This should be of size 0 as transaction is not commited yet
System.out.println(entitiesCommited.size())
}
So What should I do to accomplish that? Or is it not possible at all?
As for environment I'm working with OSGi and Aries JPA/JTA but I think this shouldn't matter here
Upvotes: 0
Views: 335
Reputation: 9
To answer my question as I already found a solution and looking forward might be useful for someone else:
The implementation of the method: List entitiesCommited=service.findCommittedEntities(...)
should be something like:
//We require a new transaction
@Transactional(value = TxType.REQUIRES_NEW)
public Entity findCommitedEntities(..){
/*This is important to create a new one. Because if we use the one we
*are using in 'mySampler()' we would be running the query in the scope
*of the other transaction and not the new one*/
EntityManager newTxEm=emf.createEntityManager()
//We join if it is not already to the new transaction
newTxEm.joinTrasaction();
[...]
// we execute whatever named query that gets all entities
[...]
return entities;
}
Upvotes: 0