how to update an entity with spring data jpa

后端 未结 5 652
鱼传尺愫
鱼传尺愫 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:48

    You must implement equals() and hashCode() in class Person.

    @Entity(name = "PERSON")
    public class Person {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "PERSON_ID")
        private Integer id;
        @Column(name = "FIRST_NAME")
        private String firstName;
        @Column(name = "LAST_NAME")
        private String lastName;
        //getters and setters
    
        @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();
        }
    }
    

提交回复
热议问题