0

Given the two line of code :

entityManager.find(MyEntity.class, myId);

((Session) getEntityManager().getDelegate()).load(MyEntity.class, myId);

The first instruction works fine, but the second one throws org.hibernate.SessionException: Session is closed!. Any idea ?

Context : spring batch 3.0.6 / hibernate 3.5.0

Info : EntityManager is injected :

@PersistenceContext
protected EntityManager entityManager;

Update 1

I can see in the find method a call to this.getSession() that open a new session if the session is null(in EntityManagerImpl.getRawSession)

Update 2

In the second situation the getSession method is not call but a class called SharedEntityManagerCreator that close the session :

if(isNewEm) {
  EntityManagerFactoryUtils.closeEntityManager(target1);
}
fego
  • 309
  • 5
  • 20
  • Are u calling the above two lines in the same flow one by one? What happens if you swap them? – Madhusudana Reddy Sunnapu Mar 17 '16 at 16:50
  • My aim is to use the hibernate session only because I need the scroll method of the Query class. So this is a simple test. I run each instruction in a different test case. – fego Mar 17 '16 at 16:53

1 Answers1

1

With proper JPA transaction management the underlying Hibernate Session should already be open. Make sure you annotate your service method with @Transactional if you're using declarative transaction management (the underlying transaction manager should be JPA aware). Should you not use declarative transaction management, you could call

entityManager.getTransaction().begin();

Don't forget to close the transaction with commit() or rollback() when you finish.

Nándor Előd Fekete
  • 6,988
  • 1
  • 22
  • 47
  • Thank you for your answer. I am using spring batch and I am inside a Reader. The transaction should be open too isn't it ? Maybe in this situation the session is not automatically open. When I look at the code of JpaPagingItemReader I can see that the EntityManager life cycle is handle is the reader. – fego Mar 18 '16 at 08:30
  • I'm not familiar with Spring Batch. It's a good practice to have all database operations use a transaction, even if read-only, because that way, at least you can get a consistent view on the database, depending on you isolation level. – Nándor Előd Fekete Mar 18 '16 at 12:31