java - Spring boot/Spring data jpa - 如何更新相关实体?
问题描述
我有以下实体:
@Entity
@Table(name = "profile")
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToOne(cascade = CascadeType.ALL)
private ProfileContacts profileContacts;
...
}
和
@Entity
@Table(name = "profile_contacts")
public class ProfileContacts {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "description")
private String description;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
}
我正在尝试通过将此带有更新的 JSON 发送到 REST 控制器来更新它:
{
"id": 1,
"description": "an update",
"profileContacts": {
"firstName": "John",
"lastName": "Doe"
}
}
所以最后它调用
profileRepository.save(profile);
profileRepository
类的实例在哪里ProfileRepository
:
public interface ProfileRepository extends JpaRepository<Profile, Long> {
}
这是spring-data-jpa
界面。
但是每次更新后它都会更新profile
表,但会向表(对应于实体的表)添加新行,而不是更新现有行。如何实现更新?profile_contacts
ProfileContacts
解决方案
根据您的 JSON 结构。profileContacts
是的,它每次都会创建新条目。
每次保存profile
您传递的实体时都会出现问题"id": 1
,这意味着 Hibernate 可以通过该id
值(主键)识别实体,但是对于profileContacts
映射,您没有发送,id
这就是 Hibernate 每次都考虑它有一个新实体的原因。
要更新您的profileContacts
实体,请确保传递它的 id。
例子:
{
"id": 1,
"description": "an update",
"profileContacts": {
"id" : yourEntityId
"firstName": "John",
"lastName": "Doe"
}
}
推荐阅读
- sql-server - 将 Oracle 语句转换为 SQL Server 格式
- solr - Solr faceting:计算“其他”类别
- python - Apache NiFi 1.10:如何将 python 脚本作为处理器执行?
- python - 给定两个数据帧,查找满足逻辑方程的所有数据帧索引
- r - 无法在 jupyter 笔记本中运行 R
- r - 使用 R 进行空间分析
- css - 如何在 Booststrap 和 wagtail 中使用 css 类
- cs-cart - 在 cs-cart 的核心 js 文件上使用 my_changes?
- node.js - Monggose / Angular / Node:使用deleteOne方法的路由一直说对象被删除但deletecount为零
- spring-boot - 禁用兔子连接