how to update an entity with spring data jpa

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

    One doesn't have to do any complex operations for this. In your service class you can do something like this.

     @Service
    public class PersonServiceImpl implements PersonService {
    
        @Autowired
        private PersonRepository personRepository;
    
        @Override
        public Person updatePerson(Person oldPerson) throws Exception { 
    
          oldPerson.setId(oldPerson.getId()) ; // pass the associated id for which you want to update and set that id to the same person [ basically setting the same id to the oldPerson ] this way it will not create new entry because here we are not making new ID ] 
    
     //oldPerson.set others [ what is to be updated ]  
    
    
            return personRepository.save(oldPerson); // now save [old person with updated content but same id as it was before ]
        }
    }
    

    This solves the problem of creating new entry to the database and updates the same content with Id associate with that person.

提交回复
热议问题