1. 导入maven
<!--mapperfacede copy神器-->
    <dependency>
        <groupId>ma.glasnost.orika</groupId>
        <artifactId>orika-core</artifactId>
        <version>1.5.4</version>
    </dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  1. 定义mapperFactory,然后定义特殊映射关系,在获取MapperFacade对象
    三个实体对象,Entity1,Entity2都一样,Entity3 吧name字段改成了name2
  2. MapperFacade高效copy工具_映射关系


  3. MapperFacade高效copy工具_映射关系_02


  4. MapperFacade高效copy工具_字段_03


  5. 下面是定义的配置文件
@Configuration
   public class MapperFacadeConfig {

    /**
     * 定义mapperFacade
     * @return
     */
    @Bean
    public MapperFacade getMapperFacade() {
        DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        addMapper( mapperFactory );
        return mapperFactory.getMapperFacade();
    }

    /**
     * 配置映特殊映射关系
     * @param mapperFactory
     */
    public void addMapper(DefaultMapperFactory mapperFactory){
        mapperFactory.classMap(Entity1.class, Entity3.class)
                .field("name","name1")//不一样的字段映射
                .byDefault()//剩余的字段映射
                .register();

    }


}
  • 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.
  1. 使用MapperFacade 复制对象
@Autowired
    MapperFacade mapperFacade;



    @Test
    public void t1() {
        Entity1 entity1 = new Entity1(2L,"name3321");

        Entity2 entity2 = mapperFacade.map(entity1, Entity2.class);
        Entity3 entity3 = mapperFacade.map(entity1, Entity3.class);

        System.out.println( "entity2:" +JSONUtil.toJsonStr( entity2 ) );
        System.out.println( "entity3:" +JSONUtil.toJsonStr( entity3 ) );

    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

结果:

MapperFacade高效copy工具_字段_04

  1. mapper 的复制不是用的反射,而是get 和 set 方法,同名字段直接复制(可以类型装换的也会自动装换),不同名字的需要单独定义,mapperfacede 会在第一次使用两个类型之间复制的时候生成对象的 get set 方法辅助类,并且缓存起来,二次复制的时候直接使用,特殊定义copy辅助类的生成时间在定义关系的时候。