Java封装orika实现对象拷贝

说明

一直使用orika复制对象,最近偶然发现了orika还有属性复制的功能,研究后封装了一下,以后用起来就更方便了

pom.xml

1
2
3
4
5
<dependency>
<groupId>ma.glasnost.orika</groupId>
<artifactId>orika-core</artifactId>
<version>1.4.6</version>
</dependency>

工具类

  • 做了简单的封装,按业务需要可以选择是否覆盖空值
  • 还有很多更灵活的配置暂时没用到,比如可以指定不同名字、不同类型字段的映射关系,这些等以后有需求的时候再加上
    BeanMapper.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    import ma.glasnost.orika.MapperFacade;
    import ma.glasnost.orika.MapperFactory;
    import ma.glasnost.orika.impl.DefaultMapperFactory;

    import java.util.List;

    /**
    * 简单封装orika, 实现深度转换Bean<->Bean的Mapper.
    */
    public class BeanMapper {

    private static MapperFacade defaultMapper;

    private static MapperFacade ignoreNullMapper;

    static {
    MapperFactory defaultMapperFactory = new DefaultMapperFactory.Builder().build();
    defaultMapper = defaultMapperFactory.getMapperFacade();
    MapperFactory ignoreNullMapperFactory = new DefaultMapperFactory.Builder().mapNulls(false).build();
    ignoreNullMapper = ignoreNullMapperFactory.getMapperFacade();
    }

    /**
    * 复制对象的属性(忽略null)
    */
    public static <S, D> void mapIgnoreNull(S sourceObject, D destinationObject) {
    ignoreNullMapper.map(sourceObject, destinationObject);
    }

    /**
    * 复制对象的属性
    */
    public static <S, D> void map(S sourceObject, D destinationObject) {
    defaultMapper.map(sourceObject, destinationObject);
    }

    /**
    * 复制对象
    */
    public static <S, D> D map(S source, Class<D> destinationClass) {
    return defaultMapper.map(source, destinationClass);
    }

    /**
    * 复制对象list
    */
    public static <S, D> List<D> mapList(Iterable<S> sourceList, Class<D> destinationClass) {
    return defaultMapper.mapAsList(sourceList, destinationClass);
    }

    }
文章目录
  1. 1. 说明
    1. 1.1. pom.xml
    2. 1.2. 工具类