如何强制Spring HATEOAS资源呈现一个空的嵌入式数组?

Chr*_*Geo 14 spring spring-hateoas

我有以下控制器方法:

@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, value = "session/{id}/exercises")
public ResponseEntity<Resources<Exercise>> exercises(@PathVariable("id") Long id) {

  Optional<Session> opt = sessionRepository.findWithExercises(id);
  Set<Exercise> exercises = Sets.newLinkedHashSet();

  if (opt.isPresent()) {
    exercises.addAll(opt.get().getExercises());
  }

  Link link = entityLinks.linkFor(Session.class)
                         .slash(id)
                         .slash(Constants.Rels.EXERCISES)
                         .withSelfRel();

  return ResponseEntity.ok(new Resources<>(exercises, link));
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我试图揭露一个特定Set<>Exercise实体Session.当exercise实体为空时,我得到一个像这样的JSON表示:

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/api/sessions/2/exercises"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

所以基本上没有嵌入式实体,而以下类似的东西是可取的:

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/api/sessions/2/exercises"
        }
    }, 
    "_embedded": {
        "exercises": [] 
    }    
}
Run Code Online (Sandbox Code Playgroud)

任何想法如何执行这个?

Oli*_*ohm 17

这里的问题是,如果没有额外的努力,就没有办法发现空集合是一个集合Exercise.Spring HATEOAS有一个帮助类可以解决这个问题:

EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
EmbeddedWrapper wrapper = wrappers.emptyCollectionOf(Exercise.class);
Resources<Object> resources = new Resources<>(Arrays.asList(wrapper));
Run Code Online (Sandbox Code Playgroud)

An EmbeddedWrapper允许您明确标记要添加到嵌入对象ResourceResources嵌入对象的对象,甚至可以手动定义它们应在其下公开的rel.正如您在上面看到的那样,帮助程序还允许您向_embedded子句添加给定类型的空集合.

  • 这会丢失泛型类型信息(并不是汇集资源时的唯一情况).我认为它应该是`EmbeddedWrapper <T>实现Resource <T>`,但是Resource不是接口,在我看来,这是Spring HATEOAS中泛型问题的根源. (2认同)
  • 我也偶然发现了这一点,我可以使用Object而不是我的EmbeddedWrapper类型来实现它,但是我真的不喜欢它。为什么这不是一个选项或默认值?当使用spring数据时,空集合也是默认的。 (2认同)
  • 请投票支持https://github.com/spring-projects/spring-hateoas/issues/522(只需点击"添加您的反应"按钮) (2认同)
  • 我对这个解决方法也不满意。它需要一些泛型杂技才能让编译器满意。我发现奇怪的是 CrudRepository 确实包含空的 _embedded json 块,而在控制器中需要此解决方法才能实现相同的结果。 (2认同)