Can I make a custom controller mirror the formatting of Spring-Data-Rest / Spring-Hateoas generated classes?
Asked Answered
S

3

27

I'm trying to do something I think should be really simple. I have a Question object, setup with spring-boot, spring-data-rest and spring-hateoas. All the basics work fine. I would like to add a custom controller that returns a List<Question> in exactly the same format that a GET to my Repository's /questions url does, so that the responses between the two are compatible.

Here is my controller:

@Controller
public class QuestionListController {

    @Autowired private QuestionRepository questionRepository;

    @Autowired private PagedResourcesAssembler<Question> pagedResourcesAssembler;

    @Autowired private QuestionResourceAssembler questionResourceAssembler;

    @RequestMapping(
            value = "/api/questions/filter", method = RequestMethod.GET,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody PagedResources<QuestionResource> filter(
            @RequestParam(value = "filter", required = false) String filter,
            Pageable p) {

        // Using queryDSL here to get a paged list of Questions
        Page<Question> page = 
            questionRepository.findAll(
                QuestionPredicate.findWithFilter(filter), p);

        // Option 1 - default resource assembler
        return pagedResourcesAssembler.toResource(page);

        // Option 2 - custom resource assembler
        return pagedResourcesAssembler.toResource(page, questionResourceAssembler);
    }

}

Option 1: Rely on the provided SimplePagedResourceAssembler

The problem with this option is none of the necessary _links are rendered. If there was a fix for this, it would be the easiest solution.

Option 2: Implement my open resource assembler

The problem with this option is that implementing QuestionResourceAssembler according to the Spring-Hateoas documentation leads down a path where the QuestionResource ends up being a near-duplicate of Question, and then the assembler needs to manually copy data between the two objects, and I need to build all the relevant _links by hand. This seems like a lot of wasted effort.

What to do?

I know Spring has already generated the code to do all this when it exports the QuestionRepository. Is there any way I can tap into that code and use it, to ensure the output from my controller is seamless and interchangeable with the generated responses?

Sexagenarian answered 23/10, 2014 at 21:56 Comment(0)
A
26

I've found a way to imitate the behavior of Spring Data Rest completely. The trick lies in using a combination of the PagedResourcesAssembler and an argument-injected instance of PersistentEntityResourceAssembler. Simply define your controller as follows...

@RepositoryRestController
@RequestMapping("...")
public class ThingController {

    @Autowired
    private PagedResourcesAssembler pagedResourcesAssembler;

    @SuppressWarnings("unchecked") // optional - ignores warning on return statement below...
    @RequestMapping(value = "...", method = RequestMethod.GET)
    @ResponseBody
    public PagedResources<PersistentEntityResource> customMethod(
            ...,
            Pageable pageable,
            // this gets automatically injected by Spring...
            PersistentEntityResourceAssembler resourceAssembler) {

        Page<MyEntity> page = ...;
        ...
        return pagedResourcesAssembler.toResource(page, resourceAssembler);
    }
}

This works thanks to the existence of PersistentEntityResourceAssemblerArgumentResolver, which Spring uses to inject the PersistentEntityResourceAssembler for you. The result is exactly what you'd expect from one of your repository query methods!

Axis answered 28/4, 2015 at 16:3 Comment(7)
Nice, I'll give try it out.Sexagenarian
See also #31759362.Zola
Small addition: You can prevent the unchecked warning, when your method directly returns PagedResource<MyEntity> this is what (paged)resourceAssembler.toResource returnsReseat
This worked except when no results were found. In that case, no _embedded key was in the REST response, unlike in an auto-generated REST/HATEOAS controller. I had to manually call pagedResourcesAssembler.toEmptyResource in this instance.Gnathous
@Gnathous maybe the Spring Data REST behaviour changed, but I also get no _embedded if a collection is empty in generated HATEOAS repositories.Minyan
@Reseat Sorry but I'm not able to remove the uncheked warning in my code. I tried what you suggested but I've always a warning on toResource() method. Thanks!Nephelometer
SDR is failing to inject the PersistentEntityResourceAssembler with Spring Boot 2.1.0. It gives java.lang.IllegalArgumentException: entities is marked @NonNull but is null.Extern
R
9

Updated answer on this old question: You can now do that with a PersistentEntityResourceAssembler

Inside your @RepositoryRestController:

@RequestMapping(value = "somePath", method = POST)
public @ResponseBody PersistentEntityResource postEntity(@RequestBody Resource<EntityModel> newEntityResource, PersistentEntityResourceAssembler resourceAssembler)
{
  EntityModel newEntity = newEntityResource.getContent();
  // ... do something additional with new Entity if you want here ...  
  EntityModel savedEntity = entityRepo.save(newEntity);

  return resourceAssembler.toResource(savedEntity);  // this will create the complete HATEOAS response
}
Reseat answered 6/1, 2017 at 19:16 Comment(10)
Is it possible to accept a link to an existing resource in the controller method arguments and convert it to an entity automagically?Foundry
Yes, if your entity links to another "child" entity, then you can simply POST a URI to create that link. e.g HTTP POST /path/to/parent/entity Payload is for ecample {someAttr: "example Value", linkToChildEntity: "/path/to/child/entity/<id>" } Hope this helps. See this stackoverflow question for far more detailsReseat
In a custom controller I mean. Spring data rest does it, I know. Question is, how can I write a controller that can do the same?Foundry
how to deal with null values? ... "PersistentEntity must not be null!"Castled
Also i am not sure how to deal with collections as e.g. GET / findAll operations. Can you provide some woking example, please?Castled
@Castled IMHO a HATEOAS REST WebService should never return just simply null. It should always at least return an empty JSON array: { }Reseat
My working example is checked in here: github.com/Doogiemuc/liquido-backend-spring/blob/master/src/…Reseat
@Reseat i totally agree ... i get that error even when the collection is not null nor empty ... maybe i have somethinf wrong. Thanks.Castled
See jira.spring.io/browse/DATAREST-657 before using this approachSpousal
@Foundry regarding your question, if you take your entity as a parameter using the Resource<> to encapsulate the entity, SDR should translate the association links to their actual entities. In the example above: @RequestBody Resource<EntityModel>Lane
S
4

I believe I've solved this problem in a fairly straightforward way, although it could have been better documented.

After reading the implementation of SimplePagedResourceAssembler I realized a hybrid solution might work. The provided Resource<?> class renders entities correctly, but doesn't include links, so all you need to do is add them.

My QuestionResourceAssembler implementation looks like this:

@Component
public class QuestionResourceAssembler implements ResourceAssembler<Question, Resource<Question>> {

    @Autowired EntityLinks entityLinks;

    @Override
    public Resource<Question> toResource(Question question) {
        Resource<Question> resource = new Resource<Question>(question);

        final LinkBuilder lb = 
            entityLinks.linkForSingleResource(Question.class, question.getId());

        resource.add(lb.withSelfRel());
        resource.add(lb.slash("answers").withRel("answers"));
        // other links

        return resource;
    }
}

Once that's done, in my controller I used Option 2 above:

    return pagedResourcesAssembler.toResource(page, questionResourceAssembler);

This works well, and isn't too much code. The only hassle is you need to manually add links for each reference you need.

Sexagenarian answered 24/10, 2014 at 16:10 Comment(4)
Sure seems like Spring could've made this a lot easier. Doesn't the fact that you have to add your own links still lead to a potentially disjointed API (like you pointed out elsewhere)? And do you have to use Pages everywhere? When I just try to return a List<Resource<MyObj>> I get recursion because of bi-directional hibernate mappings. So I either have to add @JsonIgnore's or use a PagedResourcesAssembler instead.Exactly
I think you want to use PagedResources and Pageable any time you are returning more than one object anyway, just for safety. Definitely it could be much easier, but you don't really end up with a disjointed API if you rely on Spring's own linkbuilder. It is possible you don't end up with links to useful destinations, but since what is relevant is up to the Controller it makes some sense. Its true Spring could probably provide useful links based on the object type returned.Sexagenarian
In 2016, is this still the best/only way to get spring-data-rest esque behavior when using a controller / custom repository? It's quite an annoyance.Foret
Sorry, I no longer work with Spring, so I can't answer what the latest technique is.Sexagenarian

© 2022 - 2024 — McMap. All rights reserved.