Cep*_*pr0 5 java spring-data-rest
我有三个实体:父级、其子级和一些参考:
家长
@Entity
@Table(name = "parents")
public class Parent extends LongId {
@NonNull
@Column(nullable = false)
private String name = "Undefine";
@NonNull
@OneToMany(cascade = MERGE)
private List<Child> children = new ArrayList<>();
}
Run Code Online (Sandbox Code Playgroud)
孩子
@Entity
@Table(name = "children")
public class Child extends LongId {
@NonNull
@Column(nullable = false)
private String name;
@NonNull
@ManyToOne(optional = false)
private Reference reference;
}
Run Code Online (Sandbox Code Playgroud)
参考
@Entity
@Table(name = "references")
public class Reference extends LongId {
@NotEmpty
@Column(nullable = false)
@Length(min = 3)
@NonNull
private String description;
}
Run Code Online (Sandbox Code Playgroud)
和他们的存储库:
@RepositoryRestResource
public interface ParentRepo extends JpaRepository<Parent, Long> {
}
@RepositoryRestResource
public interface ChildRepo extends JpaRepository<Child, Long> {
}
@RepositoryRestResource
public interface ReferenceRepo extends JpaRepository<Reference, Long> {
}
Run Code Online (Sandbox Code Playgroud)
之前,我坚持了几个孩子的参考。然后我用一个孩子创建了一个新的 Parent:
POST http://localhost:8080/api/parents
{
"name" : "parent2",
"children" : [
"http://localhost:8080/api/children/3"
]
}
Run Code Online (Sandbox Code Playgroud)
并已成功获得状态 201 Created。但是当我尝试将另一个孩子添加到parent2 时(用 PATCH 更新它):
PATCH http://localhost:8080/api/parents/2
{
"name" : "parent2",
"children" : [
"http://localhost:8080/api/children/3",
"http://localhost:8080/api/children/4"
]
}
Run Code Online (Sandbox Code Playgroud)
我有一个错误:
{
"cause": {
"cause": null,
"message": "Can not construct instance of restsdemo.domain.entity.Child: no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/api/children/4')\n at [Source: N/A; line: -1, column: -1]"
},
"message": "Could not read payload!; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of restsdemo.domain.entity.Child: no String-argument constructor/factory method to deserialize from String value ('http://localhost:8080/api/children/4')\n at [Source: N/A; line: -1, column: -1]"
}
Run Code Online (Sandbox Code Playgroud)
如果我从 Child 中删除指向 Reference 实体的链接:
POST http://localhost:8080/api/parents
{
"name" : "parent2",
"children" : [
"http://localhost:8080/api/children/3"
]
}
Run Code Online (Sandbox Code Playgroud)
一切正常 - child4成功添加到parent2。
如果子实体引用了另一个实体,您能否指出如何正确更新子实体列表?
这个例子的回购在这里:https : //github.com/Cepr0/restdemo
我简直不敢相信!我向 Child 添加了一个带有 String 参数的空构造函数,一切正常!
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "children")
public class Child extends LongId {
@NonNull
@Column(nullable = false)
private String name;
@NonNull
@ManyToOne(optional = false)
private Reference reference;
public Child(String reference) {
}
}
Run Code Online (Sandbox Code Playgroud)
谁能解释为什么它有效?
| 归档时间: |
|
| 查看次数: |
2399 次 |
| 最近记录: |