Home > front end >  MapStruct spring boot
MapStruct spring boot

Time:01-08

Does anyone know why mapStruct doesn't allow DTO class to have less elements than the ENTITY class.

for example I have this entity :

public class Provider {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @OneToMany(cascade=CascadeType.ALL, mappedBy="provider")
    private Set<Product> products;

}

and the dto :




public class ProviderDTO {

    private Long id;
    private String name;

}

the Dto doesn't contain the attribute 'products' which give me this error: tap to see image if the error

ps: when i add List to the DTO, everything works fine. But i want that my DTO class contains only the attributs that I want, not the same ones as in the Entity class.

CodePudding user response:

When your source and target objects are not identical, you need to define the difference in your mapper class's mapping method.

  1. If source and target object has different names of properties you need to define which property name of source will be mapped to which property name of the target.

  2. If target does not have a property but the source has, you need to specify ignore for that property on the mapping method.

    @Mapping(target = "products", ignore = true)

CodePudding user response:

Looking at the error message it seems that you have the DTO objects, the entity objects and the mapper most likely each in their own modules. But when adding them to the end product you are using versions that aren't matching with the functionality needed.

The generated mapper that is being used expects the List object in the DTO class. But the supplied DTO information doesn't have this. Which means that the mapper needs to be updated so that it knows that the DTO class doesn't have this field.

In code:

// DTO module version 2
class DTO {
  private String field1;
  private String field2;
  // removed: private List<String> list1;
  // leaving out setters/getters
}

// Entity module version 1
class Entity {
  private String field1;
  private String field2;
  private List<String> list1;
  // leaving out setters/getters
}

// Mapper module version 1 with dependencies on:
//   DTO module version 1
//   Entity module version 1
interface Mapper {
  DTO EntitytoDto(Entity source);
}

@Generated
class MapperImpl {
  DTO EntitytoDto(Entity source) {
    // mapping code for field1, field2 and list1.
  }
}

End result of the above code is a NoSuchMethodError when it tried to map list1.

What you want is:

// Mapper module version 2 with dependencies on:
//   DTO module version 2
//   Entity module version 1
interface Mapper {
  DTO EntitytoDto(Entity source);
}

@Generated
class MapperImpl {
  DTO EntitytoDto(Entity source) {
    // mapping code for field1 and field2.
  }
}

Hope this helps with solving the issue.

  • Related