MapStruct

When working with Spring services and exposing REST API calls, you would usually want to have a set of customized objects exposed to the outside world. These objects, usually called DTOs, can expose some of the domain objects or some projection made out of domain objects (or something else).

For mapping between domain data objects and DTO objects, instead of writing mappers yourself, you can use MapStruct.

MapStruct is a code generator that greatly simplifies the implementation of mappings between Java bean types based on a convention over configuration approach. The generated mapping code uses plain method invocations and thus is fast, type-safe and easy to understand.

Here is an example from the mapstruct.org (Car, CarDTO and a mapper).


    public class Car {
     
        private String make;
        private int numberOfSeats;
        private CarType type;
     
        //constructor, getters, setters etc.
    }


    public class CarDto {
     
        private String make;
        private int seatCount;
        private String type;
     
        //constructor, getters, setters etc.
    }


        @Mapper 
        public interface CarMapper {
         
            CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); 
         
            @Mapping(source = "numberOfSeats", target = "seatCount")
            CarDto carToCarDto(Car car); 
        }

So, lets say we have very simple mapping between two classes, Product and ProductDTO. If there are no customization (field names match), then mapper is as simple as:

@Mapper
public interface ProductMapper {
    ProductDto productToProductDto(Product product);
    Product productDtoToProduct(ProductDto productDto);
}

There are some good resources on using mapstruct, so instead of reinventing the wheel, here are two good places to start, mapstruct.org and a great tutorial.