繁体   English   中英

播放框架:在Interceptor Action类中使用JPAEntityManager

[英]Play Framework: Using JPA entityManager in Interceptor Action class

我正在使用@With(Action.class)批注来拦截对特定控制器/动作的调用。 我正在尝试在拦截器函数中从数据库中检索会话; 但是,Action.class拦截器方法“调用”中没有JPA帮助器类。

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

谢谢。

拦截器类别:

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将您的动作包装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注释方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM