【问题标题】:Transactional annotation not working in spring boot 2.1.3事务注释在 Spring Boot 2.1.3 中不起作用
【发布时间】:2019-07-15 07:40:56
【问题描述】:

@Transactional 注释在 springboot-hibernate 项目中对我不起作用。我正在使用已完成以下配置的注释配置。我曾尝试在服务层和 dao 层中使用 @Transactional on 方法和类名,但没有运气。我认为事务管理器配置存在一些问题,但我无法弄清楚如何在我的应用程序中配置事务管理器。

application.properties

#spring configuration
spring.jpa.show-sql = true
#spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

@Autowired
    private EntityManagerFactory entityManagerFactory;
    @Override
    public void deleteSMS(String id) {
        logger.info("Delete sms details with id :: \"" + id + "\"");
        Session session = null;
        try {
            session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
            SMSDetails smsDetails = session.get(SMSDetails.class, Long.parseLong(id));
            if (smsDetails != null)
                session.delete(smsDetails);
        } catch (Exception e) {
            logger.error("Error occured while deleting the sms with id :: \"" + id + "\" :: " + e.getMessage());
            throw e;
        } finally {
            if (session != null)
                session.close();
        }
    }

服务

@Override
    @Transactional
    public void deleteSMS(String id) {
        smsDao.deleteSMS(id);
    }

我正在使用 spring boot 2.1.3 和休眠。我已经像上面一样配置了 entitymanagerfactory 并使用以下内容来获取会话

session = entityManagerFactory.unwrap(SessionFactory.class).openSession();

@Transactional 不起作用

【问题讨论】:

  • SessionFactory 也需要由 spring 以及 AFAIK 管理。此外,您仅在事务开始后才打开会话。这在逻辑上是错误的

标签: java spring hibernate spring-boot kotlin


【解决方案1】:

我遇到了同样的问题 我在我的班级申请中添加了这个注释 @EnableTransactionManagement (proxyTargetClass = true)

这在我的班级服务的方法上

@Transactional (rollbackFor = Exception.class)

【讨论】:

    【解决方案2】:

    您正在@Transactional 方法中打开Session。这是错误的,因为当您将方法注释为事务性时,它是在单个会话中调用的,您不需要打开另一个。

    【讨论】:

    • 我使用 getCurrentSession 而不是 openSession 但问题仍未解决,我认为问题在于事务管理器的初始化。我通过展开 entityManagerFactory 创建会话对象,但在这种情况下我无法弄清楚如何实例化事务管理器
    猜你喜欢
    • 2015-09-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2019-12-18
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多