Java Play框架:在拦截器操作类中使用JPA entityManager
我正在使用@With(Action.class)注释拦截对特定控制器/操作的调用。我试图在拦截器函数中从上的数据库检索会话;但是,JPA helper类在Action.class拦截器方法“call”中不可用 是否有人可以指导如何在拦截器函数中检索数据库实体 谢谢 拦截器类别:Java Play框架:在拦截器操作类中使用JPA entityManager,java,jpa,playframework,playframework-2.0,Java,Jpa,Playframework,Playframework 2.0,我正在使用@With(Action.class)注释拦截对特定控制器/操作的调用。我试图在拦截器函数中从上的数据库检索会话;但是,JPA helper类在Action.class拦截器方法“call”中不可用 是否有人可以指导如何在拦截器函数中检索数据库实体 谢谢 拦截器类别: public class SecuredAction extends Simple { public SecuredAction() { // TODO Auto-generated const
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);
}
}
公共类SecuredAction扩展了简单{
公共安全{
//TODO自动生成的构造函数存根
}
@凌驾
公共承诺呼叫(上下文ctx)抛出可丢弃{
//检查isContactVerified/isEmailVerified
字符串sid=getSidFromCookie(ctx);
如果(sid!=null){
会话appSession=(会话)JPA.em().createNamedQuery(“Session.findBySessionId”).getSingleResult();
User=appSession.getUserId();
如果(用户!=null){
ctx.args.put(“用户”,用户);
返回委托呼叫(ctx);
}
}
Result unauthorized=Results.unauthorized(“无效会话”);
返回F.Promise.pure(未经授权);
}
私有字符串getSidFromCookie(Http.Context ctx){
返回ctx.session().get(AppConstants.COOKIE\u USER\u SESSIONID);
}
}
错误:
[运行时异常:没有绑定到此线程的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);
}
);
如果使用(SecuredAction.class)
@注释方法,则不要使用@Transactional
注释方法。最后,我创建了一个单独的数据库服务,分别从Java持久性中获取entityManager实例,并从拦截器代码中调用该静态方法。对于上述情况,您能建议哪种方法(使用Transaction或单独的EM getInstance)是最佳实践吗?这完全取决于您。如果你的代码不会给你带来麻烦,那就去做吧。