Transactional annotation not working in spring boo

2019-08-30 22:48发布

问题:

@Transactional annotation is not working for me in a springboot-hibernate project. I am using the annotation configuration for which i have done the following configuration. I have tried using the @Transactional on method and class name in the service layer and also in the dao layer, but no luck. I think there is some issue with the transaction manager configuration but I am unable to figure out how to configure the transaction manager in my application.

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

dao

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

service

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

I am using spring boot 2.1.3 and hibernate. I have configured the entitymanagerfactory as above and used the following to obtain session

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

but the @Transactional is not working

回答1:

You are opening a Session inside a @Transactional method. This is wrong, because when you annotate method as transactional, it is invoked inside a single session, you don't need to open another one.



回答2:

I had the same problem I added this annotation on my class application @EnableTransactionManagement (proxyTargetClass = true)

And this on the method on my class service

@Transactional (rollbackFor = Exception.class)