【发布时间】:2016-11-20 07:59:21
【问题描述】:
在 Spring Rest Controller 中使用 PUT 请求方法部分更新实体时,我试图区分空值和未提供的值。
以以下实体为例:
@Entity
private class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/* let's assume the following attributes may be null */
private String firstName;
private String lastName;
/* getters and setters ... */
}
我的个人存储库(Spring Data):
@Repository
public interface PersonRepository extends CrudRepository<Person, Long> {
}
我使用的 DTO:
private class PersonDTO {
private String firstName;
private String lastName;
/* getters and setters ... */
}
我的 Spring RestController:
@RestController
@RequestMapping("/api/people")
public class PersonController {
@Autowired
private PersonRepository people;
@Transactional
@RequestMapping(path = "/{personId}", method = RequestMethod.PUT)
public ResponseEntity<?> update(
@PathVariable String personId,
@RequestBody PersonDTO dto) {
// get the entity by ID
Person p = people.findOne(personId); // we assume it exists
// update ONLY entity attributes that have been defined
if(/* dto.getFirstName is defined */)
p.setFirstName = dto.getFirstName;
if(/* dto.getLastName is defined */)
p.setLastName = dto.getLastName;
return ResponseEntity.ok(p);
}
}
请求缺少属性
{"firstName": "John"}
预期行为:更新 firstName= "John"(保持 lastName 不变)。
带有空属性的请求
{"firstName": "John", "lastName": null}
预期行为:更新 firstName="John" 并设置 lastName=null。
我无法区分这两种情况,因为 DTO 中的lastName 总是由 Jackson 设置为 null。
注意: 我知道 REST 最佳实践 (RFC 6902) 建议使用 PATCH 而不是 PUT 进行部分更新,但在我的特定场景中我需要使用 PUT。
【问题讨论】:
标签: java json rest spring-mvc jackson