使用spring数据rest发布嵌套对象?

使用spring数据rest发布嵌套对象?,spring,spring-boot,spring-data-jpa,spring-data-rest,spring-hateoas,Spring,Spring Boot,Spring Data Jpa,Spring Data Rest,Spring Hateoas,我最近开始在我的应用程序中使用SpringDataREST。我拥有以下JPA实体: @Entity public class Super { @Id private long id; @JoinTable @OneToMany(cascade = CascadeType.ALL) private List<Child> children; } ----------------------------------------- @Entit

我最近开始在我的应用程序中使用SpringDataREST。我拥有以下JPA实体:

@Entity
public class Super {
    @Id
    private long id;

    @JoinTable
    @OneToMany(cascade = CascadeType.ALL)
    private List<Child> children;
}

-----------------------------------------

@Entity
public class Super2 {
    @Id
    private long id;

    @JoinTable
    @OneToMany(cascade = CascadeType.ALL)
    private List<Child> children;
}

-----------------------------------------

@Entity
public class Child {
    @Id
    private long id;

    @Column
    private String childMetadata;
}
@实体
公共级超级{
@身份证
私人长id;
@可接合
@OneToMany(级联=级联类型.ALL)
私人名单儿童;
}
-----------------------------------------
@实体
公共级超级2{
@身份证
私人长id;
@可接合
@OneToMany(级联=级联类型.ALL)
私人名单儿童;
}
-----------------------------------------
@实体
公营儿童{
@身份证
私人长id;
@纵队
私有字符串元数据;
}
我可以想出两种方法来保存
Super
Super2
的新实例:

  • 在创建
    Super
    Super2
    的实例之前,为
    Child
    类->创建
    Child
    的所有实例公开
    @RestResource
    资源->在
    Super
    Super2
    的有效负载中传递所有
    Child
    实例的URL
  • Super
    Super2
    的有效负载中传递
    Child
    的详细信息,而不公开
    @RestResource
    Child
    类和
    级联类型。所有
    都将负责创建
    Child
    实例
  • 这两种方法都有一些优点:

  • 使用选项1,我可以通过
    POST
    将新
    Child
    的url添加到
    http://:/Super/1/children
    ,向
    Super
    Super2
    添加新的
    Child
    对象。但如果使用这种方法,我肯定会失去数据库的级联功能
  • 使用选项2,我获得了数据库的所有级联功能,但我失去了添加新
    实例的灵活性
  • 有什么我完全错过的吗?我希望有一种方法可以使用数据库的级联功能,而不会失去动态添加新子项的灵活性


    谢谢你的帮助。:)

    第三种解决方案应该适合您:

  • 在Super或Super2的有效负载中传递Child的详细信息,而不公开Super(和Super2)的属性children的@RestResource
  • 您仍然可以使用
    /children
    ,但您可以使用super检索子级并发布它

    要做到这一点,只需更改Super(和Super2)类,如下所示:

    public class Super {
        @Id
        @GeneratedValue
        private Long id;
    
        @JoinTable
        @OneToMany(cascade = CascadeType.ALL)
        @RestResource(exported=false)
        private List<Child> children;
    
        ...
    }
    

    我个人不使用spring数据rest。根据我的经验,只要每个实体只有一个视图(JSON表示),它在读取数据时工作得相当好。然而,编写数据通常更复杂,因为您必须管理关系,这通常需要自定义代码。另外,当您从JSON反序列化创建实体时,您必须对分离的JPA实体有相当多的了解,这是大多数开发人员所不知道的。大多数开发人员最好为JSON视图编写单独的DTO,并编写服务方法来持久化数据。
    {
        "children": [
            {
                "childMetadata": "inner"
            }
        ]
    }