我正在使用 JPA (hibernate)、JAX-RS (Jersey) 和 Jackson。
在构建并发送数据包后,如何关闭实体管理器?
以下内容不起作用并给我一个错误。它似乎在响应完成之前调用 em.close() 。
@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] 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"])
我正在其他类似的方法中使用事务。
最佳答案
解决此问题的方法是创建一个过滤器 - 该过滤器将在为您管理事务的 jaxb servlet 之前运行。网上有一些这样的例子。
该模式称为“在 View 中打开 session ”。在堆栈溢出流上,您可以尝试 Filter do not initialize EntityManager和其他地方看看...
http://www.naildrivin5.com/daveblog5000/?p=39
http://chstath.blogspot.com/2007/11/extending-transaction-boundaries-beyond.html
但您也可以尝试在 Google 或 Stack Over Flow 上搜索以获取更多帮助。
关于java - 与 Jackson 和 Jax-rs 一起使用时如何关闭实体管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10441039/