Saksham Gupta
Saksham Gupta

Reputation: 223

How does @Transactional work outside controllers in Play! Framework?

I was trying to implement my own method interceptors using annotations (Guice) in Play!. However, it seems like those annotations would only work (and therefore intercept) if the containing classes are created by Guice (reference). That brings me to the question: How does @Transactional work outside of Controller classes in Play!? It is essentially a method interceptor, and it works fine no matter how the containing classes were created? I can use it within my models and service classes as well.

Upvotes: 3

Views: 1063

Answers (1)

dzagorovsky
dzagorovsky

Reputation: 921

@Transactional doesn't work outside a controller. Your only way is to use JPA.withTransaction

Example:

public Promise<Integer> doWork() {
    return promise(() -> jpaApi.withTransaction(() -> {
        return JPA.em()
            .createNativeQuery("DELETE FROM table WHERE id=1")
            .executeUpdate();
    }), dbExecutionContext);
}

Or even without additional execution context (executes in the caller thread):

public Promise<Integer> doWork() {
    return jpaApi.withTransaction(() -> {
        return JPA.em()
                .createNativeQuery("DELETE FROM table WHERE id=1")
                .executeUpdate();
    });
}

Don't forget to inject play.db.jpa.JPAApi.

Upvotes: 3

Related Questions