首页 > 解决方案 > 从具有多个实体的映射器中获取一个实体

问题描述

假设您有两个实体在数据库 Ent1 和 Ent2 中定义对象,以及一个描述二合一的 DTO。
我的 MapStruct EntitiesDtoMapper 映射器看起来像:

@Mapper
interface EntitiesDtoMapper{
    DTO EntitiesToDto(Ent1 ent1, Ent2 ent2);
    //It is possible to do this?
    Ent1 DtoToEnt1(DTO dto);
}

我喜欢从 DTO 获取 Ent1 和 Ent2,这可能吗?

标签: javadtomapstruct

解决方案


对谁感兴趣;这是可能的,但要注意实体参数的名称。
这里有一个例子:

@Data @Entity
public class Ent1{
  public Ent1() {}
  String id;
  String name;
}

@Data @Entity
public class Ent2{
  public Ent2() {}
  String id;
  String name;
}

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class DTO{
  String id1,id2,name1,name2;
}

@Mapper
public interface EntitiesDtoMapper{  

  EntitiesIcspDtoMapper INSTANCE = Mappers.getMapper(EntitiesDtoMapper.class);

  @Mappings({
    @Mapping(source="ent1.id", target = "id1"),
    @Mapping(source="ent1.name", target = "name1"),
    @Mapping(source="ent2.id", target = "id2"),
    @Mapping(source="ent2.name", target = "name2")
  })
  DTO EntitiesToDto(Ent1 ent1, Ent2 ent2);

  @Mappings({
    @Mapping(source="id1", target = "id"),
    @Mapping(source="name1", target = "name"),
  })
  Ent1 DtoToEnt1(DTO dto);

  @Mappings({
    @Mapping(source="id2", target = "id"),
    @Mapping(source="name2", target = "name"),
  })
  Ent2 DtoToEnt2(DTO dto); 

}

推荐阅读