Spring Data Rest-具有关系的POST不会持久存在依赖实体

时间:2019-04-10 11:33:21

标签: spring-data-jpa spring-data spring-data-rest

我正在尝试使用SDR 3.1.6和RestTemplate保留2个依赖实体,它们的定义如下:

    @Entity
    public class Child {

        @Id
        @GeneratedValue
        private long id;

        [getters/setters omitted]
    }

    @Entity
    public class Parent {

        @Id
        @GeneratedValue
        private long id;

        @OneToOne(cascade = CascadeType.ALL)
        private Child child;

        [getters/setters omitted]
    }

由于Parent拥有Child,因此我的保留顺序如下

    RestTemplate restTemplate = new RestTemplate();

    Child child = restTemplate.postForObject("server-url/children", new Child(), Child.class);

    Parent parent = new Parent();
    parent.setChild(child);
    Parent created = restTemplate.postForObject("server-url/parents", parent, Parent.class);

结果不是我所期望的,因为createdParent.getChild()的结果是null,并且查询server-url/parents显示了一个parent并链接到child,从而导致遵循404。

    _embedded: {
      parents: [
        {
          _links: {
            self: {
              href: "server-url/parents/2"
            },
            parent: {
              href: "server-url/parents/2"
            },
            child: {
              href: "server-url/parents/2/child"
            }
          }
        }
      ]
    }

但是有一个Child对象持久存在,可以由server-url/children来查询

    _embedded: {
      children: [
        {
          _links: {
            self: {
              href: "server-url/exported-children/1"
            },
            child: {
              href: "server-url/exported-children/1"
            }
          }
        }
      ]
    }

我认为我遵循了Spring Data Rest文档,但是这里有些糟糕。任何人都可以启发我。

0 个答案:

没有答案