0

I have asynchronous web service method in which I want to send response 202 (Accepted), and do same changes with DB. How can I implement it with JPA? Here my service method:

@Transactional
public void createTask(@Suspended AsyncResponse response){
    new Thread(){
        public void run(){
            RequestTask requestTask = new RequestTask();
            requestTask.setAim("all tables");
            requestTask.setDescription("Update Tables");
            requestTask.setOwner("John Calagan");

            requestTaskDao.createRequestTask(requestTask); 
        }

    }.start();

    Response acceptedResponse = Response.status(Response.Status.ACCEPTED).build();
    response.resume(acceptedResponse);
}

My Dao level:

@PersistenceContext(unitName = "administration")
private EntityManager entityManager;

@Override
public void createRequestTask(RequestTask requestTask) {
    entityManager.persist(requestTask);
}

But I have an exception:

Exception in thread "Thread-6" javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call  at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityMa nagerInvocationHandler.invoke(SharedEntityManagerCreator.java:282) at com.sun.proxy.$Proxy33.persist(Unknown Source) at... 

How can I resolve this problem?

Jason Aller
  • 3,391
  • 28
  • 37
  • 36
Vas9IH
  • 3
  • 3

2 Answers2

0

You should move all actual code from run to separate class and mark method with Transactional annotation. It force Spring to do its runtime magic.

Then inject this servise class to your and call it.

PS: Moving code to new method of your unnamed class will not help.

talex
  • 15,633
  • 2
  • 24
  • 56
0

Generally, it's not recommended to create thread in JEE applications. See Java EE specification and multi threading how to do it properly.

If you still want to create you own thread, make sure that you do NOT create the bean yourself, but have spring create it, using ApplicationContext.getBean() . Then Spring will be able to do it's magic. (Again, this is also not recommended, see here Why is Spring's ApplicationContext.getBean considered bad? )

Community
  • 1
  • 1
Guenther
  • 1,935
  • 2
  • 13
  • 20