0

I'm using Spring Data REST to build my application. It's been working very well so far, but I'd like to add some customizations to returned entity while still keeping the automatically generated links.

I'd like to do something like this:

@RepositoryRestController
public class SomeController {

    @GetMapping("/entity/{id}")
    public SomeEntity getEntity(@PathVariable int id)
        SomeEntity entity = SpringDataREST.findById(id); //-> is there a way to do this?

        Link randomLink = generateRandomLink();
        entity.addLink(randomLink);

        //do other stuff with entity

        return entity;
    }
}

Where SomeEntity class extends Spring HATEOAS ResourceSupport.

SHTJ
  • 13
  • 4
  • What does this `randomLink` supposed to refer to ? If you send it back with `entity`, how does this `randomLink` refers to the state of the `entity` – piy26 May 31 '18 at 08:16
  • It's just an example of a "customize the returned entity" – SHTJ May 31 '18 at 09:20

1 Answers1

0

If you are using Spring Data REST you can use RepositoryEntityLinks to programmatically create links:

@Component
public class MyBean {

    private final RepositoryEntityLinks entityLinks;

    public MyBean(RepositoryEntityLinks entityLinks) {
        this.entityLinks = entityLinks;
    }

    public Link someMethod(MyEntity entity) {
        //... 
        return entityLinks.linkToSingleResource(entity)
    }
}

Note - to use linkToSingleResource method, the MyEntity must implement Identifiable interface. Instead you can use method linkForSingleResource:

return entityLinks.linkForSingleResource(MyEntity.class, entity.getId())
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
Cepr0
  • 28,144
  • 8
  • 75
  • 101
  • This is helpful, though it appears that RepositoryEntityLinks only works within the scope of a REST request. If you're writing any code that interacts with the Java repository interfaces directly (e.g., interface a `PersonRepository extends JpaRepository<...>`), then RepositoryEntityLinks dies with an IllegalStateException ("No current ServletRequestAttributes"), since it tries to construct the URI using `ServletUriComponentsBuilder.fromCurrentServletMapping()`. – Joshua Taylor Jul 05 '19 at 14:54