Search code examples
hibernateserializationhibernate-mappingjava

How to limit hibernate related objects during serialization


My question is not how to get rid of cyclical dependence, I know how.

And even more so in our example, I will use a unidirectional connection.

Let's say we have a lot of related objects:

@Entity
public class EntityOne {

    @OneToMany
    private Set<EntityTwo> entityTwoCollection;

}

@Entity
public class EntityTwo {

    @OneToMany
    private Set<EntityThree> entityThreeCollection;

}

@Entity
public class EntityThree {

    @OneToMany
    private Set<EntityFour> EntityFourCollection;

}

...
// 4, 5 ... 20

If we do nothing and try to serialize the first object (EntityOne) in the controller, provided that it has connections, we will get all twenty serialized objects, which is not necessary and very expensive.

For my case, I need for the first object (EntityOne) to get related objects only to the third. And for the second object (EntityTwo), do not display related objects at all, only your fields.

The question is, what techniques should I use in order to display objects in my API to a certain depth. In order not to make queries to the database for objects that I do not need to display.


Solution

  • This is perfect example of why we should not expose our entities directly through an API, but instead use some form of DTO. This allows for a clear separation of internal representation from external representation. For those using Spring REST, the dto is an extension of Resource. In many of my projects, I use Dozer to map between entity and dto. Dozer does wildcard mapping, meaning any fields of the same name and with compatible types it will map automatically (there no mapping to write). Any fields not in your DTO will not be mapped.