2017-04-20 250 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之间的映射,我会建议使用新界面,以便您可以在需要的地方重复使用它