ModelMapper匹配策略:标准参考类型

时间:2017-09-26 09:21:41

标签: modelmapper

实体类:

@

DTO:

class User{
    private Name name;
    private int age;
    private String email;
    private Date dob;
    private Address address;

  // No Arguments Constructor , All Arguments Constructor , Setters, Getters and toString
}


class Name {
    private String firstName;
    private String lastName;

   // No Arguments Constructor , All Arguments Constructor , Setters, Getters and toString
}

class Address {
    private String houseNo;
    private String street;
    private String city;
    private Integer pincode;

    // No Arguments Constructor , All Arguments Constructor , Setters, Getters and toString
}

将实体转换为DTO的代码:

class UserDTO{
    private String firstName;
    private String lastName;
    private int age;
    private String email;
    private Date dob;
    private String houseNo;
    private String street;
    private String city;
    private Integer pincode;

   // No Arguments Constructor , All Arguments Constructor , Setters, Getters and toString
 }

输出:

public class ReferenceTypePropertiesMapper {

@Test
public void shouldPopulateAllSimpleProperties(){
    User user = createUser();
    ModelMapper modelMapper = new ModelMapper();
    UserDTO userDTO = modelMapper.map(user,UserDTO.class);

    System.out.println("Source : "+ user);
    System.out.println("Destination : "+ userDTO);
}

private User createUser(){
    Name name = new Name("Siva", "Prasad");
    Address address = new Address("1-93","ABC","HYD",123456);
    return new User(name, 29, "Siva@gmail.com", new Date(), address);
  }
}

我在User.java中使用了2个引用类型名称地址。 在为User创建对象时,我也传递了Name和Address的详细信息。当我尝试将用户对象映射到 UserDTO 时,名称详细信息已成功映射,但地址详细信息不是得到映射。

任何人都可以帮助我理解为什么会这样讨厌或者我错过任何东西吗?

1 个答案:

答案 0 :(得分:0)

使用MatchingStrategies.LOOSE一切正常。

  

松散匹配策略允许源属性与目标属性松散匹配,方法是要求层次结构中的最后一个目标属性匹配。以下规则适用:

     
      
  • 可以在任何订单
  • 中匹配代币   
  • 最后一个目标媒体资源名称必须包含所有匹配的订单
  •   
  • 最后一个源属性名称必须至少一个标记匹配
  •   
     

松散匹配策略非常适合用于具有非常不同的属性层次结构的源和目标对象模型。 可能会导致检测到更高级别的模糊匹配,但对于众所周知的对象模型,它可以是定义映射的快速替代方法

这样就必须只添加一行:



    @Test
    public void shouldPopulateAllSimpleProperties() {
        User user = createUser();
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
        UserDTO userDTO = modelMapper.map(user, UserDTO.class);

        System.out.println("Source : " + user);
        System.out.println("Destination : " + userDTO);
    }

输出:

Source : User{name=Name{firstName='Siva', lastName='Prasad'}, age=29, email='Siva@gmail.com', dob=Wed Oct 18 23:44:25 MSK 2017, address=Address{houseNo='1-93', street='ABC', city='HYD', pincode=123456}}
Destination : UserDTO{firstName='Siva', lastName='Prasad', age=29, email='Siva@gmail.com', dob=Wed Oct 18 23:44:25 MSK 2017, houseNo='1-93', street='ABC', city='HYD', pincode=123456}