简体   繁体   中英

Custom Spring Data Rest Controller with HATEOAS Support

I am implementing Spring Data REST in one of my project. I have to write a few custom Repository in order to write custom queries. I am using a Controller in front of my REST Repository. In order to get a HATEOAS response, I am using PersistentEntityResourceAssembler in my controller. This controller works fine for a single entity but in case of a list, I get an exception "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);
        }
    }

I am trying to leverage maximum spring functionality with minimum coding support from my end. I do not want to write a ResourceAssembler for each and every persistent entity in my project.

Please suggest if anyone has any ideas.

To work with list of 'resources' you can use class Resources , for example, like this:

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

From Resources javadoc:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM