也许我很幸运,但是我尝试使用@RepositoryRestResource
实现存储库,但是未在子级中设置父级的外键。我将尝试解释我所做的事情和发现的事情。
首先让我们展示一下我所做的事情:
UML:
我的马铃薯实体:
@Data
@Entity
@Table(name = "POTATO")
public class PotatoEntity {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger id;
@Column(name = "FIRSTNAME")
private String firstname;
@Column(name = "LASTNAME")
private String lastname;
@OneToMany(mappedBy = "potato", cascade = CascadeType.PERSIST)
private List<DetailPotatoEntity> detailPotatoList;
}
我的DetailPotato实体:
@Data
@Entity
@Table(name = "DETAIL_POTATO")
public class DetailPotatoEntity {
@Id
@Column(name = "ID")
private BigInteger id;
@Column(name = "WEIGHT")
private BigDecimal weight;
@Column(name = "HEIGHT")
private BigDecimal height;
@JoinColumn(name = "POTATO_ID", nullable = false)
@ManyToOne
@JsonBackReference(value = "potato-detailPotato")
private PotatoEntity potato;
}
我的马铃薯仓库:
@RepositoryRestResource(collectionResourceRel = "potatos", path = "potatos")
public interface PotatoRepository extends CrudRepository<PotatoEntity, BigInteger> {
}
问题是当我推送以下json时:
{
"firstname":"patate",
"lastname":"potato",
"detailPotatoList": [
{
"weight":12,
"height":13
}
]
}
POTATO_ID
中的DETAIL_POTATO
始终为空。通常,当您拥有自己的控制器和服务时,可以在每个PotatoEntity
中设置DetailPotatoEntity
,一切都会好起来的。因此,我坚信@RepositoryRestResource
会为我做到。.事实并非如此。
我如何“解决”它?还是我?:
@PrePersist
public void prePersist() {
detailPotatoList.forEach(detailPotato-> detailPotato.setPotato(this));
}
OR
public void setDetailPotatoList(List<DetailPotato> detailPotatoList) {
detailPotatoList.forEach(detailPotato-> detailPotato.setPotato(this));
this.detailPotatoList = detailPotatoList;
}
我的问题是,我必须这样做是正常的吗? @RepositoryRestResource
是否应该自行管理?
这是我的观察结果:
-也许@RepositoryRestResource
仅应用于一个实体?
-我尝试了一个DetailPotatoRepository来查看(以防您自己检查,请注意,需要删除由PotatoRepository
表示的@RepositoryRestResource
才能起作用):
@RepositoryRestResource(collectionResourceRel = "detailsPotato", path = "detailsPotato")
public interface DetailPotatoRepository extends CrudRepository<DetailPotatoEntity, BigInteger> {
}
当我推送以下json时:
{
"weight":12,
"height":13,
"potato": {
"firstname":"pomme",
"lastname":"apple"
}
}
POTATO_ID
已设置好,一切都很好。
结论
当父母告诉他的孩子坚持住时,孩子们不知道谁是他的父母。但是,当孩子告诉父母要坚持下去时,孩子就会认识父母。
这里又是一个问题:@RepositoryRestResource
是否应该自行管理?还是@RepositoryRestResource
应该只用于一个实体?
答案 0 :(得分:1)
您正在使用双向关联。在这种情况下,您应提供synchronization个实体。尝试在您的Potato#detailPotatoList
设置器中实施此设置。像这样:
public void setDetailPotatoList(List<DetailPotatoEntity> details) {
if (detailPotatoList != null) {
detailPotatoList.forEach(d -> d.setPotato(null));
}
if (details != null) {
details.forEach(d -> d.setPotato(this));
}
detailPotatoList = details;
}
请参阅我的example。