Damith Ganegoda
Damith Ganegoda

Reputation: 4328

How do I connect with play persistence (JPA) in Akka actors?

I'm using play framework and JPA. Few messages are passed to the Akka Actors to async processing. Inside async process, I need to connect my database through JPA.

public class OrderCreation extends UntypedActor {

    private EntityManagerFactory emFact = null;
    private ActorSelection provisioner;

    @Transactional(readOnly = false)
    @Override
    public void onReceive(Object order) throws Exception {
        //HERE I need to do JPA related transactions



    }

    @Override
    public void postStop() throws Exception {
    }

    @Override
    public void preStart() throws Exception {
        provisioner =getContext().actorSelection("/user/OrderProvisioner");
        emFact = Persistence.createEntityManagerFactory("test-data-play");

    }
}

I got this error

[akka://application/user/OrderCreation] No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread.
java.lang.RuntimeException: No EntityManager bound to this thread. Try wrapping this call in JPA.withTransaction, or ensure that the HTTP context is setup on this thread.
    at play.db.jpa.JPA.em(JPA.java:58)

Anybody has an idea to connect JPA through Akka?

Upvotes: 1

Views: 950

Answers (1)

RP-
RP-

Reputation: 5837

@Transactional is an action composition, it will only work in Controllers.

You need to inject JPAApi in your actor and use jpaApi.withTransaction method to create/attach EntityManager to the thread and wrap you code within a transaction.

Upvotes: 1

Related Questions