fego
fego

Reputation: 311

JPA - Hibernate session is closed, but entitymanager works

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);
}

Upvotes: 0

Views: 5404

Answers (1)

Nándor Előd Fekete
Nándor Előd Fekete

Reputation: 7118

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.

Upvotes: 1

Related Questions