Currently settings up classic mappers, converting Entities to DTOs. Some of the entities (and thus DTOs) reference each other (after specific JPA entity definition).
Let's say:
public class Person {
private String name;
private List<State> states; // All states with this person
// Getters & Setters
}
public class State {
private String name;
private List<Person> persons; // All persons with this state
// Getters & Setters
}
With such circular dependencies I have to set up mappers like so:
public class PersonMapper {
public PersonDTO toDTO(Person p) { // not null
PersonDTO dto = new PersonDTO();
dto.setName(p.getName());
dto.setStates(p.States().stream().map(stateMapper::toDTO).collect(Collectors.toList());
return dto;
}
public class StateMapper {
public StateDTO toDTO(State s) { // not null
StateDTO dto = new StateDTO();
dto.setName(s.getName());
dto.setPersons(s.getPersons().stream().map(personMapper::toDTO).collect(Collectors.toList());
return dto;
}
One way to easily avoid this is to create a new method in PersonMapper or StateMapper and make it NOT map the persons or states. But I was wondering if there was a known design pattern or a more generic way of doing this?
Thanks
Aucun commentaire:
Enregistrer un commentaire