Spring Data Rest : Foreign key is update with null after post call in one to many relationship

前提是你 提交于 2019-12-05 06:37:02

I have had the exact problem, the issue stems from the declaration of table relationship. From UpdateEntity to DailyUpdateEntity, you are declaring the relationship in the following form;

@OneToMany(mappedBy = "updateEntity", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<DailyUpdateEntity> dailyUpdateEntities = new HashSet<>();

which causes the issue, by separating the insertion of dependent entity, and addition of foreign key to it. So first create operation will always lack a foreign key. With the following declaration, this issue is resolved, and creation will contain a foreign key;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "update_id", nullable = false, updatable = false)
private Set<DailyUpdateEntity> dailyUpdateEntities = new HashSet<>();

It seems the problem is that you try to persist the relation on the wrong side.

You are posting an UpdateEntity (against the UpdateRepository) where you mapped the Set<DailyUpdateEntity> collection as mappedBy = "updateEntity" which means that this is just the readonly side of the bidirectional association and there will be no connection between the entities.

You would face a not-null constraint error if you would enhance the DailyUpdateEntity mapping like:

@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "update_id")
private UpdateEntity updateEntity;

Maybe you should adjust your mapping or think about another storing strategy / order.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!