Home > Software engineering >  RestController with a mapping to retrieve entity with or without children
RestController with a mapping to retrieve entity with or without children

Time:02-17

I'm sure this should be simple, but I just can't seem to figure out how to do this.

We have an entity with a oneToMany relationship to another entity. Basic parent/child relationship (Using Spring/JPA).

The requirement is to have an api '/parents' which provides all of the parents and another '/parents_with_children' that provides all of the parents and their related child entities.

Now to get the parents with their children, we can specify "@OneToMany(fetch = FetchType.EAGER) and this is working fine.

But, how can I tell my RestController class to return only the top level components without cascading?

// Works fine with eager fetching
@GetMapping("/parents_with_children")
public List<Parent> list() {
    return ParentService.getParents();
}

// How can I tell this one to NOT print out the children?
@GetMapping("/parents")
public List<Parent> list() {
    return ParentService.getParents();
}

Should I manually print & return JSON data from the entities some how?

CodePudding user response:

You can use a DTO pattern (simple POJO) as an abstraction of your Entity. You can define these such as ParentDto and create all the methods that you want to return in the JSON.

The idea is to grab your entity from the DB, map it to the DTO. In the case of your /parents without children, you would simply not set the children list (leave it null).

You can then mark that field with @JsonInclude(JsonInclude.Include.NON_NULL) which will only show this field in the JSON if it's set.

public class ParentDto {

   @JsonInclude(JsonInclude.Include.NON_NULL)
   private List<Children> children;
    
   
   // other private members
   // getters/setters
}

There are a few libraries that can do the mapping for you such as mapstruct or ModelMapper or you can map the Parent entity to ParentDto yourself.

Then your controller would return DTOs.

public List<ParentDto> list();
  • Related