我正在使用ModelMApper将对象从DTO映射到Impl - 在反序列化对象时.这与JAxRS结合使用.当用户发出POST/PUT请求时,我不希望映射"id".
我需要跳过所有映射的"id"字段.我不想一个接一个地做这个,因为没有必要为所有类显式地图.如何配置映射器以跳过从所有DTO到Impls映射的所有"id"字段.
谢谢
我有员工对象列表 - 列表我需要将其转换为员工转移对象列表 - 列表
假设两个类中都存在字段"password".
示例代码段:
List<Employee> employees = employeeRepository.findAll();
// Define the target type
Type targetListType = new TypeToken<List<EmployeeDTO>>() {}.getType();
List<EmployeeDTO> employeeDTOs = modelMapper.map(employees, targetListType);
Run Code Online (Sandbox Code Playgroud)
请让我知道如何跳过映射/复制字段.
当我尝试通过枚举将源中的字符串映射到目标中的整数时。模型映射器失败。
来源
public class Request {
private String classification;
}
Run Code Online (Sandbox Code Playgroud)
目的地
public class DTO {
private Integer classification;
}
Run Code Online (Sandbox Code Playgroud)
字符串和整数之间的映射在 ENUM 中定义
public enum Classification {
POWER(3, "Power"),
PERFORMANCE(4, "Performance"),
TASK(13, "Task");
private final Integer code;
private final String name;
ProblemClassification(final int code, final String name) {
this.code = code;
this.name = name;
}
public Integer getCode() {
return code;
}
public String getName() {
return name;
}
public static Integer getCodeByName(String name) {
Optional<Classification> classification = Arrays.asList(Classification.values()).stream()
.filter(item -> …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,我使用 ModelMapper 库将数据传输对象映射到实体。
一个实体Library有一个包含其他实体的集合( java.util.Set) Book。用户应该能够更改集合内容。
UpdateDTO在这种情况下,使用包含Book要存储在集合中的实体的标识符的数据传输对象。
后端使用映射UpdateDTO到实体。LibraryModelMapper
现在假设用户Book从 集合中删除一个实体Library。nowUpdateDTO包含所有实体的列表,其中Book没有被用户删除的实体。
我希望集合在将 映射到实体Book时缺少用户删除的实体。但与我的预期不同的是,返回的实体仍然包含所有实体。ModelMapperUpdateDTOLibraryLibraryBook
这是为什么?我已将“问题”确定为CollectionConverter[0] 中的这些行。
我想对我的实体之一进行部分更新,但如果一个属性为空,则要更新的实体也会将该值设置为空。我希望如果源中的某个属性为空,则保留源中的属性。
我已经尝试过这个但没有运气:
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
modelMapper.createTypeMap(String.class, Date.class);
modelMapper.addConverter(new StringToDate());
modelMapper.addConverter(new DateToString());
return modelMapper;
}
Run Code Online (Sandbox Code Playgroud)
然后我像这样更新我的对象:
@Override
public void editUser(final User user) {
UserDocument userDocument = this.usersRepository.findByIdAndActivo(user.getId(), true)
.orElseThrow(UserNotFoundException::new);
userDocument = this.modelMapper.map(user, UserDocument.class);
this.usersRepository.save(userDocument);
}
Run Code Online (Sandbox Code Playgroud)
该user对象有 1 个属性设置为 null,而该对象userDocument有一个值,然后当我将它保存在数据库中时,该值消失了(因为它已转换为 null)。
有什么问题吗?
谢谢。
我有剩余模型,用于构建发送的 JSON。
休息模型
@Getter @Setter
@ToString
public class OrderRequestModel {
private String orderKeyId;
private String paymentMode;
private double totalAmount;
private List<ProductRequestModel> orderProducts;
private UserDetailsRequestModel seller;
private Date createdAt;
}
Run Code Online (Sandbox Code Playgroud)
ProductRequestModel 类似
@Getter @Setter
@ToString
public class ProductRequestModel {
private String productKeyId;
private String name;
private double price;
private int qty;
private String imgPath;
private CategoryRequestModel category;
}
Run Code Online (Sandbox Code Playgroud)
我将模型传递到与数据库相关的 DTO 层(它们包含一个长 ID):
@Getter @Setter
@ToString
public class OrderDto implements Serializable {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private static final long serialVersionUID = 1L;
private …Run Code Online (Sandbox Code Playgroud) 我有一个将双精度数转换为字符串的转换器。在转换之前,我想将双精度格式格式化为固定的小数位数。但我注意到它没有被调用。这是我的方法:
我的两个模型具有相同的属性名称。
private String price; // my DTO
private Double price; // my JPA entity
Run Code Online (Sandbox Code Playgroud)
这是我的 modelMapper bean ModelMapperConfig.java:
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
modelMapper.getConfiguration().setAmbiguityIgnored(true);
modelMapper.addConverter(convertDoubleToString());
return modelMapper;
}
private Converter<Double, String> convertDoubleToString() {
return mappingContext -> Utility.formatDoubleToString(mappingContext.getSource());
}
Run Code Online (Sandbox Code Playgroud)
正在ModelMapper将我映射Double到String罚款。
但它不遵守格式化的小数位。知道我缺少什么吗?
我正在尝试反序列化以下格式的 JSON 文件:
[
["AA", "GG", "1992/11/18"],
["BB", "DD", "2005/02/20"]
]
Run Code Online (Sandbox Code Playgroud)
使用这个类:
public class DataList {
private List<String> att;
// constructor, getter and setter
}
Run Code Online (Sandbox Code Playgroud)
正在做:
DataList [] dataList= mapper.readValue(ResourceUtils.getFile("classpath:" + filename), DataList [].class);
Run Code Online (Sandbox Code Playgroud)
但我得到:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.example.DataList ` out of START_ARRAY token
at [Source: (File); line: 2, column: 3] (through reference chain: java.lang.Object[][0])
Run Code Online (Sandbox Code Playgroud)
关于如何修复此错误有什么想法吗?
我一直在应用程序周围使用 modelmapper 和 java 8Options,它们工作得很好,因为它们是原始类型;直到我将模型对象的字段之一更改为可选类型。然后一切都崩溃了。事实证明,许多库不能很好地处理泛型。
这是结构
public class MyObjectDto
{
private Optional<MySubObjectDto> mySubObject;
}
public MyObject
{
privae Optional<MySubjObject> mySubObject;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试映射MyObjectDto到时MyObject, modelmapper 调用
public void setMySubObject(Optional<MySubObject> mySubObject){
this.mySubObject = mySubObject;
}
Run Code Online (Sandbox Code Playgroud)
with Optional<MySubObjectDto>,我不明白这怎么可能(它们之间没有继承)。当然,崩溃得很快。现在我已经改变了我的设置器以接受 Dto 类型只是为了度过这一天,但这从长远来看是行不通的。有没有更好的方法来解决这个问题,或者我应该创建一个问题?
我正在重构我的代码。我想在我的 DTO 中使用 java 记录而不是 java 类。要将 DTO 转换为实体,我使用的是 ModelMapper(2.3.5 版)。当我尝试获取有关用户的信息(调用方法将实体转换为 DTO)时,出现此错误。
Failed to instantiate instance of destination xxx.UserDto. Ensure that xxx.UserDto has a non-private no-argument constructor.
这是我的代码。
public record UserDto(String firstName,
String lastName,
String email,
String imageUrl) {}
Run Code Online (Sandbox Code Playgroud)
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private ModelMapper modelMapper;
@GetMapping("/user/me")
@PreAuthorize("hasRole('USER')")
public UserDto getCurrentUser(@CurrentUser UserPrincipal userPrincipal) {
return convertToDto(userRepository.findById(userPrincipal.getId())
.orElseThrow(() -> new ResourceNotFoundException("User", "id", userPrincipal.getId())));
}
private UserDto convertToDto(User user) {
UserDto userDto = modelMapper.map(user, UserDto.class);
return …Run Code Online (Sandbox Code Playgroud) modelmapper ×10
java ×7
converters ×1
enums ×1
java-14 ×1
java-8 ×1
java-record ×1
jax-rs ×1
json ×1
model ×1
option-type ×1
spring ×1
spring-boot ×1