2021年3月12日星期五

Each time same object is persisted using JPA a new row is inserted in database

Having this class annotated with javax.persistence.* annotations:

@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;      }  }  

When saved an object X of this class in Database using Spring JpaRepository interface save(S entity) method, it is generated an Id for this object and saved in Database.

But then, if the object X state changes and it is saved again using the save(S entity) method it is not updated the old row in Database but a new row is created. I guess this behaviour is because the object id was not updated after been autogenerated the first save message returns (it seems it is needed a flush operation between).

So this is not working:

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  

By the way the documentation for save(S entity) method says:

Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.

Does it mean the object we pass as parameter to save method is a different object that the one it is returned, with possibly a different state?

https://stackoverflow.com/questions/66603115/each-time-same-object-is-persisted-using-jpa-a-new-row-is-inserted-in-database March 12, 2021 at 11:52PM

没有评论:

发表评论