how to update an entity with spring data jpa

后端 未结 5 641
鱼传尺愫
鱼传尺愫 2021-01-31 11:18

I have an entity and a Junit, I want to test that update method is working fine, but when I invoke save method from CrudRepository I get a new entry in my table instead of the u

5条回答
  •  礼貌的吻别
    2021-01-31 11:33

    Two ways to make this work

    override compareTo method as

    @Entity(name = "PERSON")
    public class Person implements Comparable{
     //... all your attributes goes here
     private Integer id;
    
     @Override
    public int compareTo(Person person) {
       return this.getId().compareTo(person.getId());
    }} 
    

    or

    you need to override equals and hashcode methods in your entity class as below

     @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (id == null || obj == null || getClass() != obj.getClass())
            return false;
        Person that = (Person) obj;
        return id.equals(that.id);
    }
    @Override
    public int hashCode() {
        return id == null ? 0 : id.hashCode();
    }
    

提交回复
热议问题