【发布时间】:2020-12-16 16:06:42
【问题描述】:
每当调用POST 时,我都想保存子实体和父实体。我有一个Item 实体,其one to one 映射到父表Attribute:
@Entity
@Table(name="Item")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Item
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private Long id;
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name="attr_id")
private Attribute attribute;
@OneToMany(mappedBy = "item", cascade = CascadeType.ALL, orphanRemoval=true)
private List<ValueSet> valueSets = new ArrayList<>();
// Other fields, getters, setters, overriding equals and hashcode using Objects.equals() and Objects.hashCode() for all the fields, helper for adding and removing ValueSet
}
Attribute 实体如下所示:
@Entity
@Table(name="Attribute")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Attribute
{
@Id
@Column(name="id")
private Long id;
// Other fields, getters, setters, NOT overriding equals hashCode
}
每当Item 被保存时,我也需要Attribute 来保存。我的邮递员发送 JSON POST 数据如下:
{
"attribute":{
"id":"6"
},
"valueSets":[
{
"value":"basic"
}
]
}
我的处理程序如下所示:
@PostMapping("/item")
public void postItems(@RequestBody Item item)
{
itemRepository.save(item);
}
ItemRepository 只是带有@Repository 注释的单行:
public interface ItemRepository extends CrudRepository<Item, Long>
当我尝试保存 Item 时遇到 - 无法将值 NULL 插入到列“attr_id”、表“项目”中;列不允许空值。插入失败。
我不明白为什么它无法将我提供的id 值 6 作为我的POST 调用的一部分。 id 值 6 已存在于 Attribute 表中。我也尝试过使用mappedBy 和CASCADE.ALL 建立双向关系,但仍然出现相同的错误。
关于我在搞砸/错过什么的任何想法/建议?此外,是否有更好的方法来处理嵌套实体?我应该尝试单独保存它们吗?在那种情况下,@RequestBody 仍然可以是父实体吗?
【问题讨论】:
标签: sql-server spring-boot hibernate spring-mvc spring-data-jpa