how to update an entity with spring data jpa

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

    The problem is in your updatePerson method in your service class. Specifically:

    return personRepository.save(oldPerson);
    

    All you are currently doing is saving a Person. That's why it is creating a second entry.
    What you should do is find the oldPerson first,

    Person p = personRepository.findOne(oldPerson.getId())
    

    then update its attributes, and then save it like you did before. Hope that helps.

提交回复
热议问题