Friday 15 February 2013

java - Jackson JSON and lazy loaded collections -



java - Jackson JSON and lazy loaded collections -

i have class lazy loads collection. have 2 different queries, 1 loads info without collection , loads whole data. when executing query doesn't load collection next error:

jsonmappingexception: failed lazily initialize collection of role: player.goals

i tried prepare using @jsoninclude(jsoninclude.include.non_empty) annotation didn't help.

how produce 2 different json results based on same class?

update: updated construction , added jsonview error didn't change.

model

@entity public class user implements serializable { @onetomany(cascade = cascadetype.all, mappedby = "owner") private collection<team> teams = new arraylist<team>(); } @entity public class team implements serializable { ... @onetomany(cascade = cascadetype.all, mappedby = "team", targetentity = player.class, fetch = fetchtype.eager) @jsonview(userviews.user.class) private collection<player> players = new arraylist<player>(); ... } @entity public class player implements serializable { @onetomany(cascade = cascadetype.all, mappedby = "player", targetentity = goal.class, fetch = fetchtype.lazy) @jsonview(userviews.userwithgoals.class) private collection<goal> goals= new arraylist<goal>(); ... }

queries

@query("select u user u u.id = :id") team findbyid(@param("id") long id);

spring controller

@requestmapping(headers = "accept=application/json") @jsonview(userviews.user.class) public @responsebody team getteam(authentication authentication) { user user = userservice.findbyid(1); homecoming team; }

with configuration accessing controller shouldn't load goalsof player class, that's mentioned part in jsonmappingexception. thought what's wrong?

maybe can take jackson jsonviews : http://wiki.fasterxml.com/jacksonjsonviews.

you have define 2 different views in entity:

@entity public class team implements serializable { ... @onetomany(cascade = cascadetype.all, mappedby = "team", targetentity = player.class, fetch = fetchtype.lazy) @jsonview(fullview.class) private collection<player> players = new arraylist<player>(); ... }

and activate view in caller method (typically jax-rs implementation - see http://wiki.fasterxml.com/jacksonjsonviews#views_with_jax-rs)

doing this, players list ignore in first case , serialized in json if list filled.

syntax should not correct, sorry, got idea

to prevent lazy can configure in spring openentitymanagerinvew filter in xml or in java (don't remember exact syntax):

<filter> <filter-name>openentitymanagerinviewfilter</filter-name> <filter-class>org.springframework.orm.jpa.support.openentitymanagerinviewfilter</filter-class> </filter> <filter-mapping> <filter-name>openentitymanagerinviewfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

hope helps

java json jpa jackson

No comments:

Post a Comment