Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelMapper - failed to convert org.hibernate.collection.internal.PersistentBag to java.util.ArrayList

How should ModelMapper configuration looks like?

compile group: 'org.modelmapper', name: 'modelmapper', version: '2.3.8'

Currently I have:

 modelMapper = new ModelMapper();
            modelMapper.getConfiguration()
                    .setMatchingStrategy(MatchingStrategies.STANDARD)
                    .setFieldMatchingEnabled(true)
                    .setFieldAccessLevel(Configuration.AccessLevel.PRIVATE);

My Entity has

@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Phones> phones = new ArrayList<>();

My second entity:

@ManyToOne
@JoinColumn(name = "employee_id")
private Employee employee;

My DTO which I want to have:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor(force = true)
public class EmployeeDTO {

@Singular
private final List<PhoneDTO> phones;

}

I am mapping this in this way:

        EmployeeDTO.EmployeeDTOBuilder employeeDTOBuilder 
= ObjectMapperUtils.map(employee, EmployeeDTO.employeeDTOBuilder.class);

I'm getting:

  1. Converter org.modelmapper.internal.converter.MergingCollectionConverter@969b4391 failed to convert org.hibernate.collection.internal.PersistentBag to java.util.ArrayList.
like image 727
Shirabu Avatar asked Nov 06 '22 05:11

Shirabu


1 Answers

Look a bit deeper in the stack trace: the last mapping problem is often something more actionable.

Maybe the PhoneDTO was not mappable ? If so, you need to create a converter and tell model mapper about it, like so:

public class PhoneConverter extends AbstractConverter<PhoneEntity, PhoneDto>
{
   private final StrictModelMapper strictModelMapper;

   @Override
   public PhoneDto convert(@NonNull final PhoneEntity source)
   {
      PhoneDto phoneDto = new PhoneDto();
      strictModelMapper.map(source, phoneDto);
      return phoneDto;
   }
}

and add it to the modelMapper.

like image 74
serv-inc Avatar answered Nov 11 '22 04:11

serv-inc