如何在与Jackson和Jax-rs一起使用时关闭实体管理器 [英] How to close an entitymanager when used with Jackson and Jax-rs

查看:186
本文介绍了如何在与Jackson和Jax-rs一起使用时关闭实体管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JPA(休眠),JAX-RS(泽西岛)和杰克逊。

I am using JPA (hibernate), JAX-RS (Jersey) and Jackson.

如何在构建和发送数据包后关闭我的实体管理器?

How can I close my entity manager after my packet is built and sent?

以下不起作用并给我一个错误。它似乎是在响应完成之前调用em.close()。

The following does not work and gives me an error. It appears to be calling em.close() before the response is completed.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getNode( @QueryParam("nodeId") long nodeId ){ 
try {
    Node node = em.find(Node.class, nodeId);        
    if (node == null) throw new WebApplicationException(Response.Status.NOT_FOUND);
    Response response = Response.ok(node, MediaType.APPLICATION_JSON).build(); 
    return response; 
 } 
finally { em.close(); }
}




SEVERE:Servlet.service()for servlet [JAX-RS Servlet]在上下文中与
path []抛出异常org.codehaus.jackson.map.JsonMappingException:
未能懒惰地初始化角色集合:
com.company。 entity.Node.childList,没有关闭会话或会话
(通过引用链:com.company.entity.Node [childIdList])

SEVERE: Servlet.service() for servlet [JAX-RS Servlet] in context with path [] threw exception org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.company.entity.Node.childList, no session or session was closed (through reference chain: com.company.entity.Node["childIdList"])

我在其他类似方法中使用交易。

I am using transactions in other similar methods.

推荐答案

解决方法是创建一个过滤器 - 它将在为您管理事务的jaxb servlet之前运行。网上有几个这样的例子。

The solution to this is to create a filter - that will run before the jaxb servlet that manages the transaction for you. There are a few examples of this on the net.

该模式被称为视图中的开放会话。在堆栈溢出流程中,您可以尝试过滤器不初始化EntityManager 和其他地方查看。 ..

The pattern is called "Open Session in View". Here on stack over flow you can try Filter do not initialize EntityManager and elsewhere look at...

http:// www.naildrivin5.com/daveblog5000/?p=39

http://chstath.blogspot.com/2007/11/extending-transaction-boundaries-beyond.html

但您也可以尝试在谷歌或堆栈上搜索更多帮助。

But you can also try and search on google or on stack over flow for more help.

这篇关于如何在与Jackson和Jax-rs一起使用时关闭实体管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆