自定义Spring Data REST控制器中如何将URI转换为实体对象?
解决Spring Data REST自定义Controller中关联URI转实体的问题
问题分析
你自定义的@BasePathAwareController中的PUT方法直接用@RequestBody Activity activity接收请求体,这绕过了Spring Data REST内置的关联资源URI到实体对象的转换逻辑——默认情况下Spring Data REST会通过HAL消息转换器和关联处理器将URI解析为对应的实体,但自定义Controller的默认消息转换器不包含这部分逻辑。
解决方案
要复用Spring Data REST的内置转换逻辑,你需要:
- 注入
DomainObjectReader:它负责将请求体内容(包括关联URI)合并到现有实体中,自动处理URI到实体的转换。 - 先从仓库获取原实体,再用
DomainObjectReader将请求体属性(含Customer的URI)应用到原实体上。 - 可选:用
PersistentEntityResourceAssembler组装符合HAL规范的响应,保持和默认接口一致的返回格式。
修改后的代码示例
@BasePathAwareController(path = "/activities") public class ActivityController extends _BaseController<Activity, Long> { private final DomainObjectReader domainObjectReader; private final ActivityRepository activityRepository; // 构造注入依赖 public ActivityController(DomainObjectReader domainObjectReader, ActivityRepository activityRepository) { this.domainObjectReader = domainObjectReader; this.activityRepository = activityRepository; } @RequestMapping(method = RequestMethod.PUT, path = "/{pos}", consumes = {MediaType.APPLICATION_JSON_VALUE, "application/hal+json"}) public ResponseEntity<PersistentEntityResource> edit( @PathVariable("pos") long pos, @RequestBody Map<String, Object> requestBody, PersistentEntityResourceAssembler assembler) { // 1. 获取数据库中已存在的实体 Activity existingActivity = activityRepository.findById(pos) .orElseThrow(() -> new RuntimeException("Activity not found")); // 2. 用DomainObjectReader处理请求体,自动将Customer URI转换为对应实体 Activity mergedActivity = domainObjectReader.read(requestBody, existingActivity); // 3. 执行你的自定义逻辑 // custom logic... // 4. 保存并返回HAL格式的响应 Activity updated = activityRepository.save(mergedActivity); return ResponseEntity.ok(assembler.toModel(updated)); } }
关键说明
- DomainObjectReader:Spring Data REST核心组件,负责将外部输入映射到实体对象,自动识别请求中的关联URI,通过Repository查找对应的实体并设置到目标对象上。
- 用Map接收请求体:避免直接用
Activity类接收时,默认消息转换器无法解析URI的问题,让DomainObjectReader全权处理转换逻辑。 - PersistentEntityResourceAssembler:生成符合HAL规范的响应体,包含关联资源的HATEOAS链接,保持和Spring Data REST默认接口一致的响应格式。
内容的提问来源于stack exchange,提问作者Meini
相关产品推荐
相关产品推荐

