支持 HATEOAS 的自定义 Spring 数据剩余控制器

Custom Spring Data Rest Controller with HATEOAS Support

我正在我的一个项目中实施 Spring Data REST。我必须编写一些自定义存储库才能编写自定义查询。我在我的 REST 存储库前面使用控制器。为了获得 HATEOAS 响应,我在控制器中使用了 PersistentEntityResourceAssembler。该控制器适用于单个实体,但如果是列表,我会遇到异常 "PersistentEntity must not be null!"

@RequestMapping(value="/employmentType", method=RequestMethod.GET, produces="application/hal+json")
    @ResponseBody
    public ResponseEntity<?> getEmploymentTypes(HttpServletRequest request, HttpServletResponse response,PersistentEntityResourceAssembler resourceAssembler) throws TenantUnavailableException, TenantInvalidException
    {
        try
        {
            List<EmploymentType> employmentTypeList = employmentTypeRepository.findAll();
            if(null==employmentTypeList || employmentTypeList.size()==0)
                return new ResponseEntity<ApiResponse>(new ApiResponse(false, ENTITY_NOT_FOUND),
                        HttpStatus.NOT_FOUND);
            // Accessing the 0th index works fine
            //In case of a full list, it throws "Persistant Entity must not be null !" exception
            return ResponseEntity.ok(resourceAssembler.toResource(employmentTypeList.get(0)));
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return new ResponseEntity<ApiResponse>(new AppResponse(false, REQUEST_NOT_PROCESSED),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

我正在尝试利用最大的 spring 功能和最少的编码支持。我不想为项目中的每个持久实体编写 ResourceAssembler。

大家有什么想法请提出来

要使用 'resources' 的列表,您可以使用 class Resources,例如,像这样:

List<EmploymentType> types = employmentTypeRepository.findAll();
Resources<Resource<EmploymentType>> resources = Resources.wrap(types);
resources.add(/* you can add some links here */);
return ResponseEntity.ok(resources);

来自 Resources javadoc:

General helper to easily create a wrapper for a collection of entities.