使用spring数据rest发布嵌套对象?
我最近开始在我的应用程序中使用SpringDataREST。我拥有以下JPA实体:使用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
@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
实例的URLSuper
或Super2
的有效负载中传递Child
的详细信息,而不公开@RestResource
的Child
类和级联类型。所有都将负责创建Child
实例
POST
将新Child
的url添加到http://:/Super/1/children
,向Super
或Super2
添加新的Child
对象。但如果使用这种方法,我肯定会失去数据库的级联功能子实例的灵活性
谢谢你的帮助。:) 第三种解决方案应该适合您:
/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"
}
]
}