xuweijsnj
xuweijsnj

Reputation: 1

mapstruct List<Long> TO List<DTO>

I’m using mapstruct 1.4.2.Final. And I having a question like this:

Business1 id has many Business2 ids relation. I want to use DTO like RelationDTO to record.

Class RelationDTO {
    private Long id;
    private Long business1Id;
    private Long business2Id;
    private String createUser;
    private LocalDateTime createTime;
}

Now I have one business1Id, and List business2IdList, want to create List< RelationDTO > By mapstruct.

@Mapper(componentModel = "spring") public interface RelationConverter {

   @Mappings({
        @Mapping(source = "business1Id", target = "business1Id"),
        @Mapping(source = "createUser", target = "createUser"),
        @Mapping(source = "createTime", target = "createTime")
})
List<RelationDTO> converteTo(List<Long> business2IdList, Long business1Id, String createUser, LocalDateTime createTime);
   

}

My question is how to coding, let business2IdList set to business2Id, and create List ?

Wating for your message, thanks.

Upvotes: 0

Views: 578

Answers (1)

programistata
programistata

Reputation: 27

I would try to solve this with default implementation for collection method and add a method for mapping object.

@Mapping(source = "business1Id", target = "business1Id")
@Mapping(source = "business2Id", target = "business2Id")
@Mapping(source = "createUser", target = "createUser")
@Mapping(source = "createTime", target = "createTime")
RelationDTO convertToRelationDto(Long business2Id, Long business1Id, String createUser, LocalDateTime createTime);

default List<RelationDTO> convertToRelationsDto(List<Long> business2IdList, Long business1Id, String createUser, LocalDateTime createTime) {
    List<RelationDTO> relations = new ArrayList<RelationDTO>();

    if (CollectionUtils.isEmpty(business2IdList)) {
        return relations;
    }

    for (Long business2Id : business2IdList) {
        relations.add(convertToRelationDto(business2Id, business1Id, createUser, createTime);
    }
}

Upvotes: 1

Related Questions