How to close an entitymanager when used with Jackson and Jax-rs

五迷三道 提交于 2019-12-24 02:13:30

问题


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

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

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] 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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/10441039/how-to-close-an-entitymanager-when-used-with-jackson-and-jax-rs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!