【发布时间】:2017-05-10 11:53:26
【问题描述】:
我有三个实体:Parent、它的 Child 和一些 Reference:
家长
@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<>();
}
儿童
@Entity
@Table(name = "children")
public class Child extends LongId {
@NonNull
@Column(nullable = false)
private String name;
@NonNull
@ManyToOne(optional = false)
private Reference reference;
}
参考
@Entity
@Table(name = "references")
public class Reference extends LongId {
@NotEmpty
@Column(nullable = false)
@Length(min = 3)
@NonNull
private String description;
}
还有他们的仓库:
@RepositoryRestResource
public interface ParentRepo extends JpaRepository<Parent, Long> {
}
@RepositoryRestResource
public interface ChildRepo extends JpaRepository<Child, Long> {
}
@RepositoryRestResource
public interface ReferenceRepo extends JpaRepository<Reference, Long> {
}
事先我坚持了几个孩子的参考。然后我创建了一个有一个孩子的新父母:
POST http://localhost:8080/api/parents
{
"name" : "parent2",
"children" : [
"http://localhost:8080/api/children/3"
]
}
并已成功获得状态 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"
]
}
我有一个错误:
{
"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]"
}
如果我从 Child 中删除指向 Reference 实体的链接:
@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;
}
一切正常 - child4 已成功添加到 parent2。
如果子实体引用其他实体,您能否指出如何正确更新子实体列表?
这个例子的回购在这里:https://github.com/Cepr0/restdemo
【问题讨论】:
-
尝试在
Parent类中添加另一个构造函数后使用此签名public Parent(String name, List<Children> children) -
谢谢@abhishek!但这没有帮助(
-
@AbhishekBhatia,我已经有一个构造函数
public Parent(String name, Child... children)并且添加你的构造函数没有帮助。 (我在每个类中都有构造函数 - 我使用 Lombock)
标签: java spring-data-rest