如何使用ModelMapper为相同的源和目标创建两种不同的映射方法?

huangapple go评论58阅读模式
英文:

How can i create two different map methods with ModelMapper for the same Source and Destination

问题

假设我有以下类:

class User {
   private String name:
   private Address address;
  // 获取器和设置器
}

class UserDto {
   private String name:
   private Address address;
  // 获取器和设置器
}

我已经创建了一个modelMapper,使我能够执行以下操作:

UserDto userDto = modelMapper.map(user, UserDto.class); // 此 map 函数将 User 类的每个字段映射到 UserDto 类

我想创建一个 modelMapper,使我能够执行以下操作:

UserDto userDto = modelMapper.mapWithoutAddress(user, UserDto.class); // 此 map 函数将 User 类的除地址外的每个字段映射到 UserDto 类

注:我正在使用一个 ModelMapper 单例,我在应用程序中使用相同的实例。

英文:

Let's say i have the following classes

class User {
   private String name:
   private Address address;
  // getters and setters
}

class UserDto {
   private String name:
   private Address address;
  // getters and setters
}

I already have created a modelMapper that allows me to do the following :

UserDto userDto = modelMapper.map(user, UserDto.class); // this map function map every field in the User class to UserDto class

And i would like to create a modelMapper that allows me to do the following :

UserDto userDto = modelMapper.mapWithoutAddress(user, UserDto.class); // this map function map every field except the adress from the User class to UserDto class

NB: i'am using a ModelMapper Singleton, i'm using the same instance in all my application.

答案1

得分: 1

根据文档所述,您可以跳过该属性。

modelMapper.typeMap(User.class, UserDto.class).addMappings(mapper -> mapper.skip(UserDto::setAddress));
英文:

As the documentation said, you could skip the property.

modelMapper.typeMap(User.class, UserDto.class).addMappings(mapper -> mapper.skip(UserDto::setAddress));

huangapple
  • 本文由 发表于 2023年5月25日 21:39:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定