@Transactional not starting transactions with Spring Boot 3 / Hibernate 6

867 views Asked by At

I am currently migrating to Spring Boot 3 / Hibernate 6. Hibernate is correctly parsing all the entities and repos, connecting to the database, etc...

However, it seems @Transactional is not starting transactions correctly.

Small example:

@Component
public class Test {

  @Autowired
  private EntityManagerFactory entityManager;

  @Transactional
  public void test() {
    Session s = entityManager.unwrap(SessionFactory.class).getCurrentSession();
    s.createQuery("FROM sometable").list();
  }
}

Error:

Caused by: org.hibernate.HibernateException: Calling method 'createQuery' is not valid without an active transaction (Current status: NOT_ACTIVE)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:341)

Relevant Config:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages="com.somepackage")
@EntityScan(basePackages="com.somepackage")
public class TransactionConfig {
...
}

session context class in application.properties

...
spring.jpa.properties.hibernate.current_session_context_class=thread
...

If I remove the above setting of session_content_class=thread, I get this error:

Caused by: org.hibernate.HibernateException: No CurrentSessionContext configured

Edit 1:

The below still results in the same error "is not valid without an active transaction"

  @PersistenceUnit
  private EntityManagerFactory entityManager;

Edit 2:

If I do not unwrap a session and just call a class with extends extends JpaRepository, it works... but it creates a new transaction and ignores the parent @Transaction

1

There are 1 answers

0
user1432882 On BEST ANSWER

Fix was the following:

    @PersistenceContext 
    private EntityManager entityManager;

and to unwrap:

    Session s = entityManager.unwrap(Session.class);