How to close entitymanager when used with Jackson and Jax-rs
I am using JPA (hibernate), JAX-RS (Jersey) and Jackson.
How can I close the Object Manager after my package has been created and submitted?
The following steps don't work and give me an error. It seems to be calling em.close () before the response completes.
@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 role collection: com.company.entity.Node.childList, the session or session is closed (via the reference chain: com.company.entity.Node ["childIdList"])
I use transactions in other ways.
source to share
The solution to this is to create a filter that will run before the jaxb servlet that handles the transaction for you. There are several examples of this on the net.
This template is called Open Session in View. Here on the stack above the thread, you can try Filter not initialize EntityManager , but elsewhere ...
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 stack through thread for more help.
source to share