Imagine having an JPA entity with different lazy loaded fields
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "organisation_teams",
joinColumns = @JoinColumn(name = "id", referencedColumnName = "id", table = "usr_organisation"),
inverseJoinColumns = @JoinColumn(name = "team_id", referencedColumnName = "id", table = "usr_teams")
)
private Set<Team> teams = new LinkedHashSet<>();
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "organisation_associations",
joinColumns = @JoinColumn(name = "parent_id", referencedColumnName = "id", table = "usr_organisation"),
inverseJoinColumns = @JoinColumn(name = "child_id", referencedColumnName = "id", table = "organisation")
)
private Set<Organisation> children = new LinkedHashSet<>();
This entity is now requested by a second service, so we need to convert into a DTO and return via REST for example. Now there can be different scenarios, where for example only the team field is required, only the children field or both.
One could map them always into the DTO, in this case using lazy loading is pointless in my opinion. Are there different elegant options aside of creating different DTOs (containing only the team or only the children fields) and different REST endpoints? I don`t think this would be an elegant solution as well, because you would end up with a bunch of endpoints and dtos.
Additionally Team and Organisation again have lazy loaded fields and the same issue applies again.
CodePudding user response:
I think that what you are looking for might be https://graphql.org/. But for plain REST endpoints I would say different DTOs is the way to go, use inheritance to avoid code duplication.
If you want to improve performance and not lazy load related entities you can specify different named entity graphs and depending on the DTO select the one that eagre loads the required data. See the documentation here: https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs001.htm.
Any lazy loaded field that is not mapped to a DTO won't be loaded. So basically you use the same entity with different graphs and different DTOs.