Mapstruct always generate mappers that use a default empty constructor and setters to construct an object.
I need mapstruct to construct objects using parameterized constructor instead.
I have this mapper configured using maptruct:
@Mapper(componentModel = "spring")
public interface FlightMapper {
FlightBooking flightBookingPostRequestDtoToFlightBooking(FlightBookingPostRequestDto flightBookingDto);
}
The implementation that mapstruct generates uses the default constructor without parameters:
public FlightBooking flightBookingPostRequestDtoToFlightBooking(FlightBookingPostRequestDto flightBookingDto) {
if ( flightBookingDto == null ) {
return null;
}
FlightBooking flightBooking = new FlightBooking();
flightBooking.setFlight_booking_id( flightBookingDto.getBooking_id() );
return flightBooking;
}
But I need this implementation with a parameterized constructor instead:
public FlightBooking flightBookingPostRequestDtoToFlightBooking(FlightBookingPostRequestDto flightBookingDto) {
if ( flightBookingDto == null ) {
return null;
}
FlightBooking flightBooking = new FlightBooking(flightBookingDto.getBooking_id());
return flightBooking;
}
How can I configure mapstruct to achieve this? I haven't found any responses in the official documentation. Thanks in advance
CodePudding user response:
You have to write a mapper, checkout their getting started guide https://mapstruct.org/
@Mapper
public interface FlightBookingMapper {
FlightBookingMapper INSTANCE = Mappers.getMapper( FlightBookingMapper.class );
@Mapping(source = "booking_id", target = "Flight_booking_id")
FlightBooking flightBookingToFlightBookingDto(FlightBooking flightBooking);
}
CodePudding user response:
Since the 1.4 release, MapStruct supports using constructors when instantiating mapping targets.
One solution would be marking the parametrized constructor as @Default
. For more possible solutions and more details on how the Constructor support works have a look at the reference guide.