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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With