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

1

8

Dependency used in Gradle:

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

Code

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);

Error

I'm getting this error:

1) Converter org.modelmapper.internal.converter.MergingCollectionConverter@969b4391 failed to convert org.hibernate.collection.internal.PersistentBag to java.util.ArrayList.

Question

How should ModelMapper configuration looks like?

Pulsimeter answered 3/9, 2020 at 6:42 Comment(0)
F
2

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.

Example for a converter

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;
   }
}

Next, add this to the modelMapper like:

modelMapper.addConverter(phoneConverter);
Fowkes answered 21/12, 2021 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.