Ошибка No transaction is in progress

Всем добрый день. Создал тестовое приложение для изучение JPA

  1. Cat_Entity
package MyPackage;

import jakarta.persistence.*;

@Entity
@Table(name = "cat")
public class Cat_Entity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY )
    @Column
    private  int id;

    @Column
    private String name;


    //сеттеры\геттеры\конструктуор 
  1. Класс конфигурация JPAConfiguration
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@ComponentScan("MyPackage")

public class JPAConfiguration {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("MyPackage");

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/sql_test");
        dataSource.setUsername("postgres");
        dataSource.setPassword("admin");
        return dataSource;
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");

        return properties;
    }
} 
  1. Cat_DAO
package MyPackage;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;

//import jakarta.transaction.Transactional;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("catDAO")

public class Cat_DAO {

    private final EntityManagerFactory entityManagerFactory;

    public Cat_DAO(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

@Transactional
    public void save(Cat_Entity cat)
    {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
     
      // entityManager.getTransaction().begin();

        entityManager.persist(cat);
        entityManager.flush();

      /*  if (entityManager.getTransaction().isActive())
            entityManager.getTransaction().commit();*/
    }
}

  1. Main
import MyPackage.Cat_DAO;
import MyPackage.Cat_Entity;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {

                try(AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JPAConfiguration.class)) {
                    Cat_DAO dao = context.getBean("catDAO", Cat_DAO.class);
                    dao.save(new Cat_Entity("Pushok"));


                }

    }
}

При запуске получаю ошибку

Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress

Подскажите, я ведь указал аннотацию @Transactional, почему не работает? Если же расскоментить строки с ручным созданием транзакции - то все работает


Ответы (1 шт):

Автор решения: Oleg Bokerov

Вопрос решился добавлением свойства

properties.setProperty("hibernate.allow_update_outside_transaction",  "true"); 

Я, правда, пока не особо понимаю полный смысл данного свойства, но как-то так

→ Ссылка