当前位置: 首页 > 知识库问答 >
问题:

MapStruct将对象映射到列表

商嘉木
2023-03-14

下面是我的DTO。

源DTO

@Data
class Source
{

String a;

String b;

String C;

}

目标DTO

@Data
class Target
{

String name;

List<Child> customList;

}

@Data
class Child
{

String attr1;

boolean attr2;

}

public interface CustomMapper
{

@Mapper(target="customList" expression="java(new Child(a,false))"
@Mapper(target="customList"  expression="java(new Child(b,true))"
@Mapper(target="customList"  expression="java(new Child(c,false))"
Target sourceToTarget(Source source);


}
List<Child> toList(Source source)
{
   List<Child> customList = new ArrayList<Child>();
   customList.add(new Child(source.getA(),false));
   customList.add(new Child(source.getB(),true)); 
   customList.add(new Child(source.getC(),false));

    return customList;
}

共有1个答案

尤钱明
2023-03-14

我有类似的用例,我想将单个对象转换为列表对象。由于这些是非常自定义的需求,mapstruct将很难为这样的用例提供一些API。

我最终使用default method实现,如下所示

@Mapper(componentModel = "spring")
interface MyMapper {
    
    default List<SomeObject> from(SourceObject sourceObject) {
      //Add Mappig logic here 
      //return the list

    }
 }

//如果要使用某个映射器进行映射

@Mapper(componentModel = "spring")
public abstract class SomeArrayMapper {

    @Autowired
    SomeMapper mapper;

    public SomeUser[] from(SingleObject singleObject) {
         SomeUsers[] Users = new SomeUser[1];
         
        Users[0] =  mapper.toUser(singleObject);;
        return Users ;
    }
}
 类似资料: