为实体列表创建一个PersistentEntityResource

时间:2018-09-05 08:26:41

标签: java spring spring-data-rest spring-hateoas

说我有一个实体类Person和一个控制器PersonController。我有一个要实现的自定义REST端点,不能使用CrudRepository方法。

这是我的PersonController的样子:

@RepositoryRestController
@RequestMapping("/people")
public class PersonController {

    @Autowired
    private PeopleRestResource peopleRestResource; //@RepositoryRestResource extending CrudRepository

    @GetMapping("/custom")
    public ResponseEntity<?> getCustomPeople(PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
        Set<Person> people = stream(this.peopleRestResource.findAll().spliterator(), true)
                .filter(/*Filter logic*/)                
                .collect(toSet());      
        return ok(persistentEntityResourceAssembler.toFullResource(people));
    }

}

这将引发IllegalArgumentException和消息PersistentEntity must not be nullpeople实际上将包含一组2个人对象,因此此错误消息起初有点令人困惑。但是,我认为此消息实际上意味着Set is not a persistent entity,就好像我只返回一个人一样,代码也可以正常运行。

@GetMapping("/custom")
public ResponseEntity<?> getCustomPeople(PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
    Person person = stream(this.peopleRestResource.findAll().spliterator(), true)
                    .filter(/*Filter logic*/)                
                    .findFirst()
                    .elseThrow(() => new IllegalStateException());


    return ok(persistentEntityResourceAssembler.toFullResource(person));
}

是否有一种方法可以利用PersistentEntityResourceAssembler来为实体列表构造HAL资源?

最好不要构造一个Resources对象并自己构造所有链接。

1 个答案:

答案 0 :(得分:1)

要返回实体列表,可以使用CollectionModel https://docs.spring.io/spring-hateoas/docs/current/reference/html/#fundamentals。您可以在PersistentEntityResourceAssembler上调用toCollectionModel()。

%%timeit
idx = df.reset_index(level=2).groupby(level=[0, 1])['level_2'].first()
idx = pd.MultiIndex.from_arrays(idx.reset_index().to_numpy().T)
df.loc[idx, :] = 0
#6.7 ms ± 40 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
df.iloc[[a[0] for a in df.groupby(level=[0, 1]).indices.values()]] = 0
#897 µs ± 6.99 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)