MapStruct

在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" );
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容