dozer的用法

更多Java知识请访问 www.itkc8.com

<dependency>
            <groupId>net.sf.dozer</groupId>
            <artifactId>dozer</artifactId>
            <version>5.5.1</version>
        </dependency>
package com.example.demo.utils;

import org.assertj.core.util.Lists;
import org.dozer.DozerBeanMapper;

import java.util.Collection;
import java.util.List;

/**
 * @author hux
 * @title: BeanMapper
 * @projectName springboot-scala
 * @description: TODO
 * @date 2019/6/20 12:59
 * @Version 1.0
 */
public class BeanMapper {

    /**
     * 持有Dozer单例
     */
    private static DozerBeanMapper dozer = new DozerBeanMapper();

    /**
     * 转换对象的类型
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        return dozer.map(source, destinationClass);
    }

    /**
     * 转换Collection中对象的类型
     */
    @SuppressWarnings("rawtypes")
    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        List<T> destinationList = Lists.newArrayList();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

    /**
     * 将对象A的值拷贝到对象B中
     */
    public static <T> T copy(Object source, T destinationObject) {
        dozer.map(source, destinationObject);
        return destinationObject;
    }

}
    public void add(List<MyStudentEntry> list){
        try {
            log.info("==="+list);
            List<MyStudent> myStudentEntries = BeanMapper.mapList(list, MyStudent.class);
            myStudentRepository.saveAll(myStudentEntries);
            log.info("--{}", myStudentEntries);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

猜你喜欢

转载自blog.csdn.net/HUXU981598436/article/details/93033319