2017-04-20 251 views
0

我有一種情況,即在DTO內部有另一個DTO,必須將其映射到其對應的實體。將DTO中的DTO映射到具有映射的實體中的實體

我使用的是地圖結構,我已經有AnotherEntityMapper已經存在。

DTO 

public class EntityDTO { 

    private AnotherEntityDTO anotherEntityDTO; 
    // other fields 
} 

Entity 

@Entity 
public class Entity { 
    private AnotherEntity anotherEntity; 
    // other fields 
} 

如何改變EntityMapper接口,這樣我可以映射到anotherEntityDTO anotherEntity?

謝謝。

回答

2

它確實取決於您使用的是哪個版本的MapStruct。 (如果您使用的版本低於1.2.0.Beta和必須的)

@Mapper 
public interface EntityMapper { 

    @Mapping(target = "anotherEntity", source = "anotherEntityDTO") 
    @Mapping(target = "anotherEntity.propE", source = "anotherEntityDTO.propD") 
    Entity map(EntityDDTO dto); 

} 

另一種選擇:如果您正在使用1.2.0.Beta或更高版本,他們可以只定義EntityMapper接口的嵌套的屬性是在增加新的方法你EntityMapper這樣的:

@Mapper 
public interface EntityMapper { 

    @Mapping(target = "anotherEntity", source = "anotherEntityDTO") 
    Entity map(EntityDDTO dto); 

    @Mapping(target = "propE", source = "propD") 
    AnotherEntity map(AnotherEntityDTO); 
} 

,或者你可以定義一個新的映射AnotherEntityMapperAnotherEntity和使用@Mapper(uses = {AnotherEntityMapper.class})

@Mapper 
public interface AnotherEntityMapper { 

    @Mapping(target = "propE", source = "propD") 
    AnotherEntity map(AnotherEntityDTO); 
} 

@Mapper(uses = {AnotherEntityMapper.class} 
public interface EntityMapper { 

    @Mapping(target = "anotherEntity", source = "anotherEntityDTO") 
    Entity map(EntityDDTO dto); 
} 

這真的取決於你的用例。如果您需要在其他地方執行AnotherEntityAnotherEntityDTO之間的映射,我會建議使用新界面,以便您可以在需要的地方重複使用它