I am using MapStruct to convert a database entity to Immutable model object. So Immutable object doesn't have setters but Mapstruct requires setters when mapping objects. So I created an explicit builder using Immutable object builder to provides to Mapstruct. Below are the snippets from code:
@Value.Immutable
@Value.Style(overshadowImplementation = true)
public interface CarModel {
@Nullable String getCarId();
}
@Mapper(uses = ImmutablesBuilderFactory.class)
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
@Mapping(source = "id", target = "carId")
ImmutableCarModel.Builder toModel(CarEntity carEntity);
}
public class ImmutablesBuilderFactory {
public ImmutableCarModel.Builder createCarModelBuilder() {
return ImmutableCarModel.builder();
}
}
Below code was generated by Mapstruct:
public class CarMapperImpl implements CarMapper {
@Autowired
private final ImmutablesBuilderFactory immutablesBuilderFactory
@Override
public Builder toModel(CarEntity carEntity) {
if ( carEntity == null ) {
return null;
}
Builder builder = immutablesBuilderFactory.createCarModelBuilder();
if ( carEntity.getId() != null ) {
builder.carId( carEntity.getId() );
}
return builder;
}
}
I was able to convert an entity to Immutable model object but unit test is failing for this. It is throwing NPE at below line of code in CarMapperImpl class while calling CarMapper.INSTANCE.toModel(carEntity).build();
in unit test
Builder builder = immutablesBuilderFactory.createCarModelBuilder();
Does anyone have any idea what's going wrong here?