{"id":1,"firstName":"string","lastName":"string","email":"ynz@hotmail.com","orders"}{"message":"Could not write JSON: failed to lazily initialize a collection of role: com.ynz.demo.springjpatransaction.entities.Customer.orders, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.ynz.demo.springjpatransaction.entities.Customer.orders, could not initialize proxy - no Session (through reference chain: com.ynz.demo.springjpatransaction.entities.Customer[\"orders\"])"}
Cause: On the surface, the exception comes from JSON parsing and meeting unexpected char; the fundamental is due to the orders are lazily fetched, but accessed outside a live persistence session. After the entity-manager loading the customer into the persistence context, and then it closed the session; afterwards accessing entity Order become impossible, and cause this exception.
Solution: keeping the persistence session open until the moment accessing the lazily loaded Entities. The optimal solution: using the Fetch join clause to fetch entity root and its aggregated entities by one query. The worst solution: making the aggregate entities become Eager-fetched, this will cause an N+1 problem, and therefore slowing down the system performance.
No comments:
Post a Comment