在mvc層經(jīng)常會(huì)遇到這樣的一種情況,是否使用DTO(數(shù)據(jù)傳輸對(duì)象),還是直接使用model返回?其實(shí)這都可以,前者叫封閉領(lǐng)域模型風(fēng)格,后者叫開(kāi)放領(lǐng)域模型風(fēng)格。因?yàn)榍罢呖梢耘懦恍┎恍枰祷氐淖侄蔚切枰M(jìn)行拷貝,后者就不需要經(jīng)過(guò)處理。另外,都會(huì)遭遇到一種情況:如性別在后臺(tái)是通過(guò)0和1,但是需要返回前端男或者女。這種情況可以使用數(shù)據(jù)字典做一個(gè)良好的處理,這個(gè)這里不談。
MapStruct可以很好的處理封閉領(lǐng)域模型風(fēng)格的model到DTO的拷貝。
https://github.com/mapstruct/mapstruct
public class CycleAvoidingMappingContext {
private Map<Object, Object> knownInstances = new IdentityHashMap<Object, Object>();
@BeforeMapping
public <T> T getMappedInstance(Object source, @TargetType Class<T> targetType) {
return (T) knownInstances.get( source );
}
@BeforeMapping
public void storeMappedInstance(Object source, @MappingTarget Object target) {
knownInstances.put( source, target );
}
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
private List<Car> team;
//constructor, getters, setters etc.
}
public class CarDto {
private String make;
private int seatCount;
private String type;
private List<CarDto> team;
//constructor, getters, setters etc.
}
@Mapper
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mappings( {
@Mapping(source = "numberOfSeats", target = "seatCount")
} )
CarDto carToCarDto(Car car, @Context CycleAvoidingMappingContext context);
@InheritInverseConfiguration
Car fromCar(CarDto carDto, @Context CycleAvoidingMappingContext context);
}
@Test
public void shouldMapCarToDto() {
//given
Car car = new Car( "Morris", 5, CarType.SEDAN );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getMake() ).isEqualTo( "Morris" );
assertThat( carDto.getSeatCount() ).isEqualTo( 5 );
assertThat( carDto.getType() ).isEqualTo( "SEDAN" );
}