How to customize ModelMapper

后端 未结 4 1582
独厮守ぢ
独厮守ぢ 2020-12-13 01:16

I want to use ModelMapper to convert entity to DTO and back. Mostly it works, but how do I customize it. It has has so many options that it\'s hard to figure out where to st

4条回答
  •  庸人自扰
    2020-12-13 01:36

    I faced a problem while mapping with ModelMapper. Not only properties but also My source and destination type were different. I solved this problem by doing this ->

    if the source and destination type are different. For example,

    @Entity
    class Student {
        private Long id;
        
        @OneToOne
        @JoinColumn(name = "laptop_id")
        private Laptop laptop;
    }
    

    And Dto ->

    class StudentDto {
        private Long id;
        private LaptopDto laptopDto;
    }
    

    Here, the source and destination types are different. So, if your MatchingStrategies are STRICT, you won't able to map between these two different types. Now to solve this, Just simply put this below code in the constructor of your controller class or any class where you want to use ModelMapper->

    private ModelMapper modelMapper;
    
    public StudentController(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
        this.modelMapper.typeMap(Student.class, StudentDto.class).addMapping(Student::getLaptop, StudentDto::setLaptopDto);
    }
            
    

    That's it. Now you can use ModelMapper.map(source, destination) easily. It will map automatically

    modelMapper.map(student, studentDto);
    

提交回复
热议问题