我正在使用@With(Action.class)注释来拦截对特定控制器/操作的调用。我试图从拦截器函数中的数据库中检索会话;但是,ActionAlass拦截器方法中没有JPA帮助程序类" 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。尝试使用@ play.db.jpa.Transactional]
注释您的操作方法答案 0 :(得分:2)
使用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);
}
);
如果您使用@Transactional
对其进行注释,请不要使用@With(SecuredAction.class)
注释方法。