Nesquik27
Nesquik27

Reputation: 254

How to configure hibernate to use Spring Data save and Session Factory with Criteria API in Spring Boot

I would like to use Spring Data (save method, that uses @Transactional with default name - "transactionManager") and my own configured Session Factory to use It, for example, in Criteria API. So I configured Session Factory, jpaVendorAdapter, DataSource, PlatformTransactionManager beans.

PlatformTransactionManager looks like:

    @Bean(name = "transactionManager")
    public PlatformTransactionManager hibernateTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
//        JpaTransactionManager transactionManager = new JpaTransactionManager();

        transactionManager.setSessionFactory(sessionFactory().getObject());
//        transactionManager.setDataSource(this.dataSource());

        return transactionManager;
    }

So, this configuration doesn't allow Spring Data save method works correctly. It doesn't throws any exception when I execute It, but It doesn't insert data as well, only update table structure. From the other hand If I use

JpaTransactionManager transactionManager = new JpaTransactionManager();

instead of HibernateTransactionManager It works fine, but other methods, that use my autowired Session Factory give me an exception: "javax.persistence.TransactionRequiredException: no transaction is in progress"

For example:

@Transactional
public List find() {
    return this.getCSession().createNativeQuery("SELECT CAST(animals.rabbit.id as VARCHAR) AS id, name FROM animals.rabbit").getResultList();
}

So, I'm interesting to use both these methods. How I can fix It?!

Upvotes: 0

Views: 203

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81882

How about using the JpaTransactionManager and use either the EntityManager instead of a Hibernate Session or if you really need a Session unwrap it from the EntityManager.

Upvotes: 0

Related Questions