Home > Blockchain >  BeanUtils.copyProperties don't copy
BeanUtils.copyProperties don't copy

Time:08-27

I try to copy one by one a list of objects into another. For this I use BeanUtils.copyProperties. But I only get the last one from the original list. I can't understand what happens. Thanks.

        try{
        List<SlideModel> slideModels = slideRepository.findAll();
        List<SlideModelDto> slideModelsDto = new ArrayList<>();
        SlideModelDto dto = new SlideModelDto();
        for (SlideModel m : slideModels) {
            BeanUtils.copyProperties(m,dto);
            System.out.println("m: "   m);
            System.out.println("slideModelDto: "   dto);
            slideModelsDto.add(dto);
        }

CodePudding user response:

List<SlideModel> slideModels = slideRepository.findAll();
List<SlideModelDto> slideModelsDto = new ArrayList<>();
SlideModelDto dto = new SlideModelDto();
for (SlideModel m : slideModels) {
    BeanUtils.copyProperties(m,dto);
    System.out.println("m: "   m);
    System.out.println("slideModelDto: "   dto);
    slideModelsDto.add(dto);
}

Your SlideModelDto is constructed outside of the loop, so the loop uses 1 instance of SliceModelDto. Hence only the last one being processed will remain as there is nothing more.

You can solve this in 2 was

  1. Move the construction of the SlideModeldto into the for loop
  2. Use streams.

As 1 is simple enough I'll give the code for solution 2.

List<SlideModel> slideModels = slideRepository.findAll();
List<SlideModelDto> slideModelsDto = 
    slideModels().stream().map(m -> {
      SlideModelDto dto = new SlideModelDto();
      BeanUtils.copyProperties(m,dto);
      return dto;
    }).collect(Collectors.toList());

That being said I would storngly suggest not to use the BeanUtils to copy properties. The javadoc clearly states Mainly for internal use within the framework. I would recommend MapStruct for the mapping, that way you define a mapper and code will be generated.

@Mapper(componentModel="spring")
public interface SlideModelToDtoMapper {
  SlideModelDto map(SlideModel sm);
}

With this you can inject and use the mapper and make the code nicer as well.

List<SlideModel> slideModels = slideRepository.findAll();
List<SlideModelDto> slideModelsDto = 
    slideModels().stream()
      .map(slideModelToDtoMapper::map)
      .collect(Collectors.toList());
  • Related