Shirabu
Shirabu

Reputation: 119

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

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?

Upvotes: 9

Views: 11184

Answers (2)

Filip
Filip

Reputation: 1

If you are using Lombok, try removing @Data annotation from that class.

In your case from EmployeeDTO. And put @Getter and @Setter annotations after you remove @Data.

Should look like this:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor(force = true)
public class EmployeeDTO {

  @Singular
  private final List<PhoneDTO> phones;

}

Upvotes: 0

serv-inc
serv-inc

Reputation: 38147

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

Upvotes: 2

Related Questions