gpt4 book ai didi

java - Play Framework : Using JPA entityManager in Interceptor Action class

转载 作者:行者123 更新时间:2023-11-30 03:21:40 26 4
gpt4 key购买 nike

我正在使用 @With(Action.class) 注释来拦截对特定 Controller /操作的调用。我试图在拦截器函数中从数据库检索 session ;然而,JPA 帮助器类在 Action.class 拦截器方法“call”中不可用。

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

谢谢。

拦截器类:

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 绑定(bind)到该线程。尝试使用 @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 注释该方法。

关于java - Play Framework : Using JPA entityManager in Interceptor Action class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31182601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com