0

Friends,

Here are my Java objects

@Data
public class CarDto {
    private String make;
    private String model;
    private int year; 
}

@Data
public class Car {
    private MakeEnum make;
    private String model;
    private int year;   
}

For consuming, I need to do something like this

@Mapper
public interface CarMapper {
   CarMapper INSTANCE = Mappers.getMapper(CarMapper.class);
   Car toModel(CarDto carDto);
   CarDto toDto(Car carModel);
}

// Using mapper
Car carModel = CarMapper.INSTANCE.toModel(carDto);

But I am looking a solution, where I could do this:

  Car carModel = Mapper.map(carDto, Car.class);

How do do this? Didn't find an example where I can dynamically map based on a Type. I found this method very handy in both ModelMapper & Google gson. Appreciate your help!

Arun Avanathan
  • 982
  • 4
  • 11
  • 26

2 Answers2

0

If I understand you correctly, you require a kind of repo.

Another option would be to look at sprint and the new MapStruct spring integration, recently developed: https://github.com/mapstruct/mapstruct-spring-extensions. It was designed as a follow up of this question.

There's an example in the example repo. It's not straightforward though: https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-mapper-repo

Sjaak
  • 3,602
  • 17
  • 29
0

Before calling the mapping, you have to setup and interface of MapStruct like this:

@Mapper(componentModel = "spring")
public interface MapStructMapper {

    ObjectDto objectToObjectDto(Object object);

}

Then an implementation of it :

@Component
public class MapStructMapperImpl implements MapStructMapper {

    @Override
    public ObjectDto objectToObjectDto(Object object) {

        if ( object == null ) { return null; }

        ObjectDto objectDto = new ObjectDto();
        objectDto.setId( object.getId() );
        objectDto.setName( object.getName() );

        return objectDto;
    }

and then, you just have to inject this interface in the controller and invoke the repository like this:

@RequestMapping("/objects")
public class ObjectController {

    private MapStructMapper mapstructMapper;

    private ObjectRepository objectRepository;

    @Autowired
    public ObjectController(
            MapStructMapper mapstructMapper,
            ObjectRepository objectRepository
    ) {
        this.mapstructMapper = mapstructMapper;
        this.objectRepository = objectRepository;
    }

    @GetMapping("/{id}")
    public ResponseEntity<ObjectDto> getById(@PathVariable(value = "id") int id){
        return new ResponseEntity<>(
                mapstructMapper.objectToObjectDto(
                        objectRepository.findById(id).get()
                ),
                HttpStatus.OK
        );
    }
    
}

Of course, you can call a service/serviceImpl instead of a direct call to the repository but it's to be as simple as possible. :)

Greg
  • 127
  • 1
  • 15