在mvc层经常会遇到这样的一种情况,是否使用DTO(数据传输对象),还是直接使用model返回?其实这都可以,前者叫封闭领域模型风格,后者叫开放领域模型风格。因为前者可以排除一些不需要返回的字段但是需要进行拷贝,后者就不需要经过处理。另外,都会遭遇到一种情况:如性别在后台是通过0和1,但是需要返回前端男或者女。这种情况可以使用数据字典做一个良好的处理,这个这里不谈。
MapStruct可以很好的处理封闭领域模型风格的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" );
}