Middle
How to update a character's name (e.g., from Vadim to Dmitry) using Spring Data, knowing its ID?
sobes.tech AI
Answer from AI
In Spring Data, to update a character's name by ID, you can do the following:
- Retrieve the entity from the database by ID using
findById. - Change the name field.
- Save the updated entity using
save.
Example:
Optional<Person> personOpt = personRepository.findById(id);
if (personOpt.isPresent()) {
Person person = personOpt.get();
person.setName("Dmitry");
personRepository.save(person);
}
If you want to update directly without loading the entity, you can use a custom query with the @Modifying and @Query annotations in the repository.