0

I have HttpServlet and it has a doPost() method in which a spring bean is used. That spring has a EntityManager defined with @PersistenceContext() defined. When the doPost() method receives a request, I get during runtime

javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

Code is something like this (pardon for writing the skeleton code):

class MyServlet extends HttpServlet {

@Autowired
SpringBean springBean;

@Override
    public void init(ServletConfig config) throws javax.servlet.ServletException{
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

@Override
doPost() {
 
   springBean.foo();
}
.
.
.

}

 @Service
 class SpringBean {
 @PersistenceContext(unitName = someUnitName)
 EntityManager entityManager;
 
 public void foo(){
 entityManager.persist(someEntity);
 }
 
 }

web.xml has the required parameters for component scan and ContextLoaderListener to make spring context available servlet. (There is an other bean without EntityManager and that's working fine)

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Sach106
  • 63
  • 6
  • Use @Transactional on foo method. It should resolve your problem – Abhijeet Sep 19 '20 at 10:59
  • I used it, but its failing with same error. Its unable to find entityManager with transaction – Sach106 Sep 21 '20 at 05:32
  • Have you enabled Spring transaction management by adding @EnableTransactionManagement on spring config class? – Abhijeet Sep 21 '20 at 06:15
  • Yes i had used EnableTransactionManagement.. Anyway, having a shared @ Configuration class with all the EntityManagers and EMFs did not work for me at all. I had to introduce a new @ Configuration class , seperated the packages and enabled component scan from two different contexts and then it seemed to be working. Not sure if that's right thing to do, but its a workaround. – Sach106 Nov 11 '20 at 05:25

0 Answers0