【问题标题】:Play Framework: Using JPA entityManager in Interceptor Action classPlay Framework:在 Interceptor Action 类中使用 JPA entityManager
【发布时间】:2015-07-02 10:54:23
【问题描述】:

我正在使用@With(Action.class) 注释来拦截对特定控制器/动作的调用。我正在尝试在拦截器函数中从数据库中检索会话;但是 JPA 助手类在 Action.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 注释您的操作方法]

【问题讨论】:

    标签: java jpa playframework playframework-2.0


    【解决方案1】:

    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 注释方法。

    【讨论】:

    • 我最终创建了一个单独的数据库服务,用于分别从 Java 持久性中获取 entityManager 实例,并从拦截器代码中调用该静态方法。您能否建议哪种方式(withTransaction 或单独的 EM getInstance)应该是上述案例的最佳实践?
    • 这完全取决于你。如果你的代码不会给你带来麻烦,那就去吧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多