java - 每次使用 JPA 持久化同一个对象时,都会在数据库中插入一个新行
问题描述
使用注释对此类进行javax.persistence.*
注释:
@Entity
public class Car{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer weight;
public setWeight(weight) {
this.weight = weight
}
public Integer getWeight() {
return this.weight;
}
}
JpaRepository
当使用 Spring接口方法将此类的对象 X 保存到 Database 中save(S entity)
时,会为该对象生成一个 Id 并保存在 Database 中。
但是,如果对象 X 状态发生变化并使用该save(S entity)
方法再次保存它,它不会更新数据库中的旧行,而是创建一个新行。我猜这种行为是因为在自动生成第一个保存消息返回后对象 id 没有更新(似乎需要在两者之间进行刷新操作)。
所以这不起作用:
Car myCar = new Car();
carJPARepository.save(myCar); --> New row in Database is inserted;
myCar.setWeight(Integer.valueOf(1000));
carJPARepository.save(myCar); --> New row is inserted in Database instead updated the first one
顺便说一句,方法的文档save(S entity)
说:
保存给定的实体。使用返回的实例进行进一步的操作,因为保存操作可能已经完全改变了实体实例。
这是否意味着我们作为参数传递给 save 方法的对象与返回的对象是不同的对象,可能具有不同的状态?
解决方案
Car myCar = new Car();
myCar = carJPARepository.save(myCar); // get the Car object with update id
myCar.setWeight(Integer.valueOf(1000));
carJPARepository.save(myCar); // calling save will now update as java object as the id
推荐阅读
- swift - 编辑器支持在 Xcode 12.4 中记录 Swift API
- sql-server-2019 - sys.sp_reset_connection 最多运行 5 分钟
- kotlin - 在共享首选项中保存按钮的颜色(kotlin)
- swift - Swift映射嵌套字典以交换外部和内部键
- c - C问题中的简单计算器
- reactjs - TailwindCSS Purgecss 在 reactjs 网站中不起作用
- javascript - 使用 puppeteer 使用标签在 a 中定位 href
- c - 使用 const char 组织字符串
- amazon-web-services - 本地 MWAA (AWS Airflow) 使用 SecretsManager 作为后端“找不到凭证”
- python - 计算分布的pdf