Hibernate and TransactionRequiredException when propagation set to Propagation.NOT_SUPPORTED

百般思念 提交于 2019-12-23 16:20:03

问题


TL;DR:

  • Service method annotated with @Transactional(propagation = Propagation.NOT_SUPPORTED)
  • Hibernate 5.0.4.Final: everything works as expected (method is executed without transaction)
  • Hibernate 5.2.5.Final: javax.persistence.TransactionRequiredException: no transaction is in progress is thrown
  • as a testcase for this issue I created a simple maven web app and the only change made in code (copy-paste from old working project) was Hibernate version bump in pom.xml

Question:

  • What is the proper way to execute service methods without transaction nowadays?

Code snippets (Spring used as a main framework):

DAO:

@Repository
public class UrlDaoImpl implements UrlDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Url> getAllUrls() {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Url");
        return query.list();
    }

}

Service:

@Service
public class UrlServiceImpl implements UrlService {

    @Autowired
    private UrlDao urlDao;


    @Override
    @Transactional // THIS WORKS IN NEW HIBERNATE
    public List<Url> getAllUrls() {
        return urlDao.getAllUrls();
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)  // THIS USED TO WORK BUT NOW THROWS EXCEPTION
    public List<Url> getAllUrlsNoTxn() {
        return urlDao.getAllUrls();
    }

}

Controller:

@Controller
public class HomeController {

    @Autowired
    private UrlService urlService;

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/plain")
    public String entryPoint() {

        urlService.getAllUrls();
        System.out.println("--------------------- ok");
        return "ok";
    }

    @RequestMapping(value = "/no-txn", method = RequestMethod.GET, produces = "text/plain")
    public String entryPointNoTxn() {

        // EXCEPTION WILL BE THROWN BELOW
        urlService.getAllUrlsNoTxn();
        System.out.println("--------------------- ok no txn");
        return "ok no txn";
    }

}

Stacktrace for the exception in new Hibernate:

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

root cause

javax.persistence.TransactionRequiredException: no transaction is in progress
    org.hibernate.internal.SessionImpl.checkTransactionNeeded(SessionImpl.java:3439)
    org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1410)
    org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1406)
    org.springframework.orm.hibernate5.SessionFactoryUtils.flush(SessionFactoryUtils.java:144)
    org.springframework.orm.hibernate5.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:95)
    org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:95)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:932)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:744)
    org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
    org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    com.sun.proxy.$Proxy32.getAllUrlsNT(Unknown Source)
    com.example.web.controller.HomeController.entryPointNoTxn(HomeController.java:31)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)

回答1:


Ok, after few hours of trying different configurations (before posting this question to SO), I finally found the solution.

For new Hibernate versions there is another required parameter that must be declared on @Transactional if you want to execute a method without a transaction: readOnly = true. So the working example of the Service part is:

@Service
public class UrlServiceImpl implements UrlService {

    @Autowired
    private UrlDao urlDao;


    @Override
    @Transactional
    public List<Url> getAllUrls() {
        return urlDao.getAllUrls();
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)  // ADDED READONLY TO WORK IN NEW HIBERNATE VERSIONS
    public List<Url> getAllUrlsNoTxn() {
        return urlDao.getAllUrls();
    }

}

I also confirmed that this works on debug by calling ((org.hibernate.engine.transaction.internal.TransactionImpl) session.getTransaction()).isActive(); which returns true for the first Service method (with transaction) and false for the second Service method (with Propagation.NOT_SUPPORTED).



来源:https://stackoverflow.com/questions/41778024/hibernate-and-transactionrequiredexception-when-propagation-set-to-propagation-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!