有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

对包含其他对象的类使用BoundedMapperFacade的java Orika映射

我有这样的课程-

class EdgeMtuMismatchEvent {
    private final List<MtuInterfaceMap> list = new ArrayList<>();
    private int id;

    // public getters and setters
}

我必须将上面的类映射到下面的类

class EdgeMtuMismatchEventUI {
    private final List<MtuInterfaceMapUI> list = new ArrayList<>();
    private int id;

    // public getters and setters
}

我知道我可以像下面这样使用地图绘制器

    final DefaultMapperFactory factory = new DefaultMapperFactory.Builder().build();
    factory.classMap(MtuInterfaceMap.class, MtuInterfaceMapUI.class).byDefault().register();
    factory.classMap(EdgeMtuMismatchEvent.class, EdgeMtuMismatchEventUI.class).byDefault().register();
//factory.getMapperFacade().map()

正如Orika performance tuning指南所说

Use BoundMapperFacade to avoid repeated lookup of mapping strategy

因此,我希望使用下面的BoundedMapperFacade来获得更好的性能

BoundMapperFacade<EdgeMtuMismatchEvent, EdgeMtuMismatchEventUI> facade = factory.getMapperFacade(EdgeMtuMismatchEvent.class, EdgeMtuMismatchEventUI.class, false)

我不知道如何在上面的代码片段中添加MtuInterfaceMap的映射器

有人能提出什么建议吗


共 (1) 个答案

  1. # 1 楼答案

    BoundMapperFacade将从映射器工厂惰性地解析映射策略,并在第一次调用map()方法时缓存它。因此,所有必需的映射定义都应该在映射器工厂中注册

    根据需要,可提供3种解决方案:

    1. 如果MtuInterfaceMapMtuInterfaceMapUI类具有相同的字段集,则无需为它们声明classMap。Orika默认情况下会复制列表元素,按名称映射字段
    2. 如果映射足够简单(例如,在具有不同名称的字段之间复制值),classMap可以声明。父类的映射将在解析映射策略时自动使用它
    3. 若需要自定义映射,可以编写自定义转换器并将其注册到MapperFactory。在本例中,父类的classMap定义需要一个使用此转换器的提示,使用fieldMap().converter()语法。自定义转换器可以通过扩展来编写,例如BidirectionalConverter<List<MtuInterfaceMap>, List<MtuInterfaceMapUI>>

    示例代码可以编写如下:

    final DefaultMapperFactory factory = new DefaultMapperFactory.Builder().build();
    
    // (1) auto-mapping
    // nothing here
    
    // (2) if the scenario is simple enough
    factory.classMap(MtuInterfaceMap.class, MtuInterfaceMapUI.class)
           .field("comment", "details")
           .byDefault()
           .register();
    
    // (3) if converter is required
    final String listConverterId = "listConverter";
    factory.getConverterMap()
           .registerConverter(listConverterId , new MtuInterfaceMapListConverter());
    
    
    // 
    factory.classMap(EdgeMtuMismatchEvent.class, EdgeMtuMismatchEventUI.class)
           .fieldMap("list", "list").converter(listConverterId).add() //  for case (3) only - declare converter
           .byDefault()
           .register();
    
    BoundMapperFacade<EdgeMtuMismatchEvent, EdgeMtuMismatchEventUI> facade =
        factory.getMapperFacade(EdgeMtuMismatchEvent.class, 
                                EdgeMtuMismatchEventUI.class, 
                                false);