Play Framework: Manually open JPA context for Spri

2019-04-15 09:03发布

I am using Spring-AMQP to monitor a RabbitMQ message queue in a Play application.

The problem is I can not access my database from the listener code since the JPA context is not open in this scope.

I understand Play Framework manages the JPA context so that it is open when processing HTTP requests, but is there a way I can use JPA from outside Play controllers/jobs?

1条回答
够拽才男人
2楼-- · 2019-04-15 09:35

Just found the answer was to use JPAPlugin!

Example listener method:

public void process(Message message) {
    JPAPlugin.startTx(false);
    boolean rollBack = false;
    try {
        // work with your models
        JPA.em().flush();
    } catch (RuntimeException e) {
        rollBack = true;
        // throw exception to prevent msg ACK, need to refine error handling :)
        throw e;
    } finally {
        JPAPlugin.closeTx(rollBack);
    }
}
查看更多
登录 后发表回答