[英]Spring Controller Patch Operation with RequestBody as list of some DTO
I have list of DTOs as requestbody to spring controller which is a patch operation.我有 DTO 列表作为 spring controller 的请求主体,这是一个补丁操作。 The patching looks starightforward,
修补看起来很简单,
--> I would iterate over the list --> 我会遍历列表
--> Get each DTO --> 获取每个 DTO
--> Get the entity object returned by findOne(id) method of JPA --> 获取JPA的findOne(id)方法返回的实体object
--> Now here I have a problem, which is checking if the field value is not null, then set it to the entity, otherwise do nothing --> 现在这里有个问题,就是检查字段值是不是null,然后设置为实体,否则什么都不做
--> I didn't want to check null value for each field and set it to the attached entity, so I used ModelMapper here. --> 我不想检查每个字段的 null 值并将其设置为附加实体,所以我在这里使用了 ModelMapper。 Please find the below code
请找到以下代码
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
modelMapper.map(someDO, someEntity); //someEntity is the one returned by findOne
tltMasterRepository.save(someEntity);
--> The problem with the null value is solved. --> null 值的问题解决了。 I would not have to explicitly check for null values before setting it to the attached entity.
在将其设置为附加实体之前,我不必明确检查 null 值。
--> But I have a few more requirements now. --> 但我现在还有一些要求。 For a few fields I wanted to perform some operation and derive some value before setting it to the attached entity.
对于一些字段,我想在将其设置为附加实体之前执行一些操作并获取一些值。 For example.. someDo.username & someEntity.userID
例如.. someDo.username & someEntity.userID
I had to get the username, call a utility method to get the userID from the username and then set this userID value to someEntity.userID.我必须获取用户名,调用实用程序方法从用户名中获取用户 ID,然后将此用户 ID 值设置为 someEntity.userID。
Similarly I have a few more fields where I have to do some pre-processing before setting it to the entity?同样,我还有一些字段在将其设置为实体之前必须进行一些预处理?
What is the best way I can do that?我能做到这一点的最好方法是什么?
Take a look at Converter
.看看
Converter
。 With convert you can extract userId from user name and set it to entity:使用 convert 您可以从用户名中提取 userId 并将其设置为实体:
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
Converter<String, String> userIdConverter = ctx -> ctx.getSource() == null ? null : Utils.extractUserId(ctx.getSource());
modelMapper.typeMap(SomeDO.class, SomeEntity.class).addMappings(mapper -> mapper.using(userIdConverter).map(SomeDO::getUsername, SomeEntity::setUserId));
modelMapper.map(someDO, someEntity);
tltMasterRepository.save(someEntity);
You can use the java bean validation with the DTO class and use @Valid @RequestBody
, for more details check out https://www.baeldung.com/javax-validation您可以使用 java bean 验证和 DTO class 并使用
@Valid @RequestBody
,有关更多详细信息,请查看httpsjava://www.baeld
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.