modelMapper使用,将数据库查询对象直接转成DTO对象

1.pom引入

<dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.3.8</version>
        </dependency>

2.将DAO对象转为DTO对象

User user = new User();
user.setId(1L);
user.setNickname("张三");
user.setEmail("101@qq.com");
user.setHonor("测试荣誉");
ModelMapper modelMapper = new ModelMapper();
UserDTO userDTO = modelMapper.map(user, UserDTO.class);
System.out.println(userDTO);

3.工具类

public class ModuleHelper {

    private static final ModelMapper modelMapper;

    static {
        modelMapper = new ModelMapper();
//        modelMapper.createTypeMap(String.class, Date.class);
//        modelMapper.addConverter(toStringDate);
//        modelMapper.getTypeMap(String.class, Date.class).setProvider(localDateProvider);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    }

    private ModuleHelper() {
    }

    public static <D, T> D map(final T entity, Class<D> outClass) {
        return modelMapper.map(entity, outClass);
    }

    public static <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
        return entityList.stream()
                .map(entity -> map(entity, outCLass))
                .collect(Collectors.toList());
    }

    public static <S, D> D map(final S source, D destination) {
        modelMapper.map(source, destination);
        return destination;
    }
}
posted @ 2021-05-12 16:47  SpecialSpeculator  阅读(677)  评论(0编辑  收藏  举报