Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 304
Saksham Gupta Avatar asked Jan 26 '26 08:01

Saksham Gupta


1 Answers

@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.

like image 159
dzagorovsky Avatar answered Jan 29 '26 00:01

dzagorovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!