I have a domain base class like this:
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class Product {
private UUID id;
private Category category;
}
The Category field is enum:
public enum Category {
BOOK("book"),
PHONE("phone");
private String name;
Category(String name) {
this.name = name;
}
public static Category fromName(String name) {
for (Category category : values()) {
if (category.getName().equals(name)) {
return category;
}
}
return null;
}
public String getName() {
return this.name;
}
}
There is a class that extends product:
@Data
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class Book extends Product {
private String title;
private String isbn;
private Author author;
}
And the DTO class:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BookDtoRest {
private String title;
private String isbn;
private Author author;
}
I want to map the BookDtoRest to Book upon receiving the request. I want the newly created book to have the parent's fields id and category populated appropriately. You can forget about the Author for the moment.
How can I do that with Mapstruct?
I would have a quick look at: bealdung
Building your project through maven / gradle, should create a BookMapperImpl class, which contains a mapping method. With the above Mapstruct will create the mapper class, as the fields are the same no custome mapping needs to be defined.
hope it helps