Deserialize lazy sleep and jackson boot

Is there a way to keep LAZY loading and deserializing an object using an identifier instead of a POJO object.

I have 2 classes that are connected by a many-to-many relationship.

Something like that

public class User { @Id @JsonProperty public long id; @ManyToMany( fetch = FetchType.EAGER, ) @JoinTable( name = "User_EntityType", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "type_id") ) @JsonProperty public Set<Type> types; } public class Type { @Id @JsonProperty public long id; @ManyToMany( fetch = FetchType.EAGER, mappedBy = "types", targetEntity = User.class ) @JsonProperty public Set<User> users; } 

The data type is working fine. I can write and read using sleep mode without any problems.

However, I want to return the User object using the REST API, so I use Jackson to deserialize. The problem is, when I do this, it deserializes each Type in the User object, which includes other type objects, and creates a huge mess.

Is it possible instead to simply return the identifiers of the Set of Long type instead of the Set of Type?

+7
source share
2 answers

Yes, it is possible if you are using Jackson 2.0 with the Object Identity feature.

If you annotate a class with the annotation @JsonIdentityInfo , then Jackson will output the object only once; subsequent links will use the identifier. This way your set of types will be serialized as identifiers, while the types will be output once. When Jackson's deserialization returns identifiers back to objects.

In your case, I think you will need to annotate the Type class as follows:

 @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") public class Type { ... } 

For more information on how to use this function, see http://wiki.fasterxml.com/JacksonFeatureObjectIdentity .

+4
source

I ran into this problem at my JAX-RS endpoints, which should serialize and serve Hibernate objects using Jackson object maps. The option of using solutions such as @JsonIgnore or @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,... , was not an option for me, since the first would mean that the relational field will be excluded from the serialized output, and the later method could not solve the problem no matter what.

So, my solution was to set the following flag on the mapper before the actual serialization:

 ObjectMapper objMapper = new ObjectMapper(); objMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 

Thus, there was no attempt to populate relational objects, instead their identifiers remained untouched, and so I could support the fetch = FetchType.LAZY in my relational fields.

0
source

All Articles