0
votes

I'm learning the Spring 4 stuff by converting an existing Spring 3 project. In that project I have a custom query. That query fetches data in a straightforward way, after which some heavy editing is done to the query results. Now the data is sent to the caller.

I plan on extending CrudRepository for most of my simple query needs. The data will be output in HATEOAS format.

For this custom query I think I should be adding custom behavior (spring.io, "Working with Spring Data Repositories", Section 1.3.1, "Adding custom behavior to single repositories").

As an example:

@Transactional(readOnly = true)
public List<Offer> getFiltered(List<Org> orgs, OfferSearch criteria) {
    List<Offer> filteredOffers = getDateTypeFiltered(criteria);
    filteredOffers = applyOrgInfo(orgs, filteredOffers);
    filteredOffers = applyFilterMatches(filteredOffers, criteria);
    return sortByFilterMatches(filteredOffers);
}

(The code merely illustrates that I don't have a simple value fetch going on.)

If I could use the raw results of getDateTypeFiltered(criteria) then I could put that into a CrudRepository interface and the output would be massaged into HATEOAS by the Spring libraries. But I must do my massaging in an actual Java object, and I don't know how to tell Spring to take my output and emit it in my desired output format.

Is there an easy way to get there from here? Or must I try things like do my filtering in the browser?

Thanks, Jerome.

2

2 Answers

0
votes

To properly get HAL formatted results, your query controllers must return some form of Spring HATEOAS Resource type.

@RequestMapping(method = RequestMethod.GET, value = "/documents/search/findAll")
public ResponseEntity<?> findAll() {

    List<Resource<Document>> docs = new ArrayList<>();
    docs.add(new Resource<Document>(new Document("doc1"), new Link("localhost")));
    docs.add(new Resource<Document>(new Document("doc2"), new Link("localhost")));

    Resources<Resource<Document>> resources = new Resources<Resource<Document>>(docs);

    resources.add(linkTo(methodOn(ApplicationController.class).findAll()).withSelfRel());
    resources.add(entityLinks.linkToCollectionResource(Document.class).withRel("documents"));

    return ResponseEntity.ok(resources);
}

I have submitted a pull request to Spring Data REST to update its reference docs to specify this in http://docs.spring.io/spring-data/rest/docs/2.4.0.RELEASE/reference/html/#customizing-sdr.overriding-sdr-response-handlers