KenavR
KenavR

Reputation: 3899

JPA manually load collections

I have an entity holding a collection (@OneToMany) which loads lazily. So far so good. If I load the entire list of entity objects (findAll()) I don't want the collection loaded at all. I don't access the collection therefore I assumed it will not be loaded before returning it from a REST endpoint, but it seems like Jackson accesses it when parsing it into JSON.

Currently I iterate over the entire entity list and set the collection to NULL. This seems like a very poor way of doing it, is there a way to ONLY manually load the collection with a specially prepared @Query and not load it automatically (either LAZY no EAGER) at all? Are @JsonViews the correct way to go or should I remove the @OneToMany annotation (I guess then I lose the mapping for the queries that actually do load the collection)? Any other suggestions?

Examplecode

@Entity

@Entity
public class Entity {
  @OneToMany(targetEntity = Child.class)
  private List<Child> children;

}

Jersey Resource

@GET
@Produces({MediaType.APPLICATION_JSON})
public List<Entity> getAllEntities() {
  List<Entity> entities = entityService.findAll();

  entities.forEach(e-> e.setChildren(null));

  return entities ;
}

Repository = JpaRepository with default findAll() implementation.

thanks

Upvotes: 0

Views: 609

Answers (2)

cassiomolin
cassiomolin

Reputation: 131187

A few time ago, I asked a question about designing model classes for a REST API. There might be some information there useful for you.

Instead of reusing the same model classes for persistence and for the REST API, I've realized the best approach was creating different models. In some situations you don't want the persistence model to be the same as the model you use in your API. So, defining different models is the way to go.

And I chose MapStruct to map from one model to other.

Upvotes: 1

yugo
yugo

Reputation: 198

Since you mentioned 'suggestion', I faced the same problem myself and I decided to implement custom DTOs to be sent in the API response. So I ommitted these collection fields and all other I did not want the json processors to touch. I did implement my set of DTOs mirroring actual persisted entities, but there might be some other mappers to do the job

Upvotes: 3

Related Questions