1

I have a Foo class and a Bar class:

@Entity
public class Foo extends BaseEntity {
    private Long id;
    private String foo;
}

@Entity
public class Bar extends BaseEntity{
    private Long id;
    private String bar;
}

And a @Controller

@Controller
...
    @RequestMapping(value = "/foo/{foo}")
    public void foo(@PathVariable("foo") Foo foo) {
...

With Spring Data JPA and Sprint REST, I'm able to pass e.g. Foo as an id in the URL and automatically get a Foo object via the built-in domain-class-converter http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web.basic.domain-class-converter:

This works fine. But in some cases I want to POST data to the controller via JSON instead of url parameter

{
    foo : {id : 42},
    bar : {id : 123},
}

Is it possible to automatically get that similarly completely loaded from JPA (and not only initialized with the id)?

I tried @RequestBody but that only initializes the values that are given by the request without loading the entity from the db.

lilalinux
  • 2,903
  • 3
  • 43
  • 53
  • Are you asking about sending JSON data using POST or how to parse given JSON to the object representation? For first check: http://stackoverflow.com/questions/17964841/how-to-get-param-in-method-post-spring-mvc – Dominik Kunicki Feb 01 '17 at 15:40
  • I'm asking about a @Controller receiving JSON – lilalinux Feb 01 '17 at 15:44
  • so this answer should help: http://stackoverflow.com/a/36849152/1653268 – Dominik Kunicki Feb 01 '17 at 15:46
  • That answer won't load the JPA entity, but initialize it only with the posted data (the id only). I would like to get the complete object as Jackson does it with @PathVariable – lilalinux Feb 01 '17 at 15:48
  • I'm afraid this is not possible. Spring Data REST uses GET method for finding data and POST for creating new instances. See 5th chapter of documentation: http://docs.spring.io/spring-data/rest/docs/current/reference/html/ – Dominik Kunicki Feb 01 '17 at 16:12
  • Maybe it could be done via registering a ConditionalGenericConverter like here https://candrews.integralblue.com/2015/07/spring-id-to-entity-conversion/ – lilalinux Feb 01 '17 at 16:14

0 Answers0