首页 > 解决方案 > 每次使用 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 方法的对象与返回的对象是不同的对象,可能具有不同的状态?

标签: javaspring-bootjpaspring-data-jpa

解决方案


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

推荐阅读