我有来自CRUD控制器的方法“更新”:
@PutMapping(value = "/{id}")
public ResponseEntity<?> update(
@PathVariable("id") Long id,
@RequestBody Entity entity
) {
repository.saveAndFlush(entity);
return ResponseEntity.ok(entity);
}
这是代码创建实体的新实例。 如何将RequestBody映射到现有实体?类似的东西:
public ResponseEntity<?> update(
@RequestBody @LoadById(@PathVariable("id")) Entity entity
)
感谢。
答案 0 :(得分:1)
映射示例:
@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
public ResponseEntity<?> update(
@PathVariable("id") Long id,
@Valid @RequestBody Entity entity
) {
Entity oldEntity = repository.findOne(id);
AnnotatedClass annotatedClass = AnnotatedClass.construct(
entity.getClass(),
objectMapper.getDeserializationConfig().getAnnotationIntrospector(),
new SimpleMixInResolver(null)
);
Iterator<AnnotatedField> fields = annotatedClass.fields().iterator();
while (fields.hasNext()) {
AnnotatedField field = fields.next();
if (!objectMapper.getDeserializationConfig().getAnnotationIntrospector().hasIgnoreMarker(field)) {
field.fixAccess();
field.setValue(oldEntity, field.getValue(entity));
}
}
repository->save(oldEntity);
return ResponseEntity.ok(oldEntity);
}