ModelMapper的简单使用

1、引入maven依赖

 
        
            org.modelmapper
            modelmapper
            2.3.0
        

        
            org.projectlombok
            lombok
            1.18.8
        

        
            junit
            junit
            4.12
        
 

2、实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Apple {

    private String id;
    private String name;
    private String createAge;

    private String age;
}

@Data
public class AppleDto {

    private String name;
    private String create_age;
    private String birth;
}

3、使用Demo

public class Demo {
    public static Apple apple;
    ModelMapper modelMapper = new ModelMapper();
    static {
        apple = new Apple("1", "red", "21", "25");
    }

    // AppleDto(name=red, create_age=null, birth=null)
    @Test
    public void test1(){
        AppleDto appleDto = modelMapper.map(apple, AppleDto.class);
        System.out.println(appleDto.toString());
    }

    // AppleDto(name=red, create_age=21, birth=null),将create_age字段改成createage也是可以正确赋值
    @Test
    public void test2(){
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
        AppleDto appleDto = modelMapper.map(apple, AppleDto.class);
        System.out.println(appleDto.toString());
    }
    // AppleDto(name=red, create_age=null, birth=25)
    @Test
    public void test3(){
        modelMapper.addMappings(customField());
        AppleDto appleDto = modelMapper.map(apple, new TypeToken(){}.getType());
        System.out.println(appleDto);
    }

    // 自定义映射规则
    private static PropertyMap customField() {

        return new PropertyMap() {
            @Override
            protected void configure() {
                map(source.getAge(), destination.getBirth());
            }
        };
    }
}

你可能感兴趣的:(java)