Play 框架:在拦截器操作中使用 JPA entityManager class

Play Framework: Using JPA entityManager in Interceptor Action class

我正在使用@With(Action.class) 注释来拦截对特定 controller/actions 的调用。我试图在拦截器函数中从数据库中检索会话;然而 JPA 助手 class 在 Action.class 拦截器方法 "call".

中不可用

有人可以指导如何在拦截器函数中检索数据库实体吗?

谢谢。

拦截器class:

public class SecuredAction extends Simple {

    public SecuredAction() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public Promise<Result> call(Context ctx) throws Throwable {
        // check isContactVerified/isEmailVerified
        String sid = getSidFromCookie(ctx);
        if (sid != null) {
            Session appSession = (Session) JPA.em().createNamedQuery("Session.findBySessionId").getSingleResult();
            User user = appSession.getUserId();
            if (user != null) {
                ctx.args.put("user", user);
                return delegate.call(ctx);
            }
        }
        Result unauthorized = Results.unauthorized("Invalid Session");
        return F.Promise.pure(unauthorized);
    }

    private String getSidFromCookie(Http.Context ctx) {
        return ctx.session().get(AppConstants.COOKIE_USER_SESSIONID);
    }
}

错误: [RuntimeException:没有绑定到此线程的 EntityManager。尝试使用 @play.db.jpa.Transactional]

注释您的操作方法

JPA.withTransaction包裹你的动作:

return JPA.withTransaction(
                "default",
                false, () -> {
                    String sid = getSidFromCookie(ctx);
                    if (sid != null) {
                        Session appSession = (Session) JPA.em().createNamedQuery("Session.findBySessionId").getSingleResult();
                        User user = appSession.getUserId();
                        if (user != null) {
                            ctx.args.put("user", user);
                            return delegate.call(ctx);
                        }
                    }
                    Result unauthorized = Results.unauthorized("Invalid Session");
                    return F.Promise.pure(unauthorized);
                }
        );

如果您使用 @With(SecuredAction.class) 注释方法,请不要使用 @Transactional 注释方法。