2

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.

Greg
  • 1,549
  • 1
  • 20
  • 34

1 Answers1

2

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.

Community
  • 1
  • 1
Michael Wiles
  • 20,902
  • 18
  • 71
  • 101