I'm trying to make an automatic mapper, but I'm having a problem with an Enum
inside my DTO.
In my @mapper
class, I want everything to be automatically mapped except fthe Enum
field. However, when debugging, I see that it does go into the mapper auto-implementation class, and it doesn't ignore my Enum
as I indicate with @mapping
Example of my Entity and DTO
@Entity
public class Document {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String type;
My DTO:
@Data
public class DocumentDTO {
private Integer id;
private DocumentsEnum type;
How can I ignore the mapping for that specific enumerated field?
I have tried the following annotations on @mapping:
@Mapper
public interface DocumentsMapper {
@Mapping(source = "type", target = "type", ignore = true)
@Mapping(source = "DocumentsEnum", target = "DocumentsEnum", ignore = true)
@Mapping(source = "MAIN", target = "MAIN", ignore = true) // <-- This is the value of Enum
@Mapping(source = "ppal", target = "ppal", ignore = true) // <-- This is the name of Enum
List<DocumentDTO> mapper(List<Document> document);
@AfterMapping
default void afterMapping(Document document, @MappingTarget DocumentDTO documentDTO) {
//some logic
}
CodePudding user response:
The correct way to declare your Mapping
to ignore the field you want to ignore is the first one, you can delete the others.
@Mapping(source = "type", target = "type", ignore = true)
The reason that this isn't working for you as written is that you are technically mapping a List
object to another List
object. The List
objects you pass in to be mapped will probably not have a type
field (and definitely not the one you care about), the objects they hold (Document
and DocumentDTO
) will though.
To get this to work they way you would like you need two mappers: one for the List
s and one for Document
to DocumentDTO
. Since the type
field you want to ignore is on the latter objects, you should put the Mapping
annotation on that method:
@Mapper
public interface DocumentsMapper {
List<DocumentDTO> listMapper(List<Document> document);
@Mapping(source = "type", target = "type", ignore = true)
DocumentDTO mapper(Document document);
The mapstruct
library is smart enough to automatically use the mapper
method to convert each element in your List
s in the listMapper
method.