I am writing an update
method in Spring Service and it says the getOne() is deprecated, I have reviewed alternatives and the findById(long id)
seems to be the go to option, but I am struggling to get this to work in my case.
I want to update the name
field of an object saved in the database. I then want to resave it in the database with the updated name.
I initially had this code with the getOne()
Society inDb = societyRepo.getOne(id);
inDb.setName(societyUpdate.getName());
societyRepo.save(inDb);
I have tried to amend this as follows,
Optional<Society> soc = societyRepo.findById(id);
soc.ifPresent(society -> society.setName(society.getName()));
societyRepo.save(soc);
but as soc
is now Optional I can't save it back in the database.
Is it acceptable to write another method in the SocietyRepo Society findbyId(long id);
which will then allow me to use Society s = societyRepo.findById(id); to get the
Societyfrom the database, update the
name` field and then resave in the database?
Assuming this all happens in a single transaction you actually don't need to call save
.
If it isn't in a single transaction, or you want to keep the call to save
for clarity, the following will work:
societyRepo.findById(id)
.ifPresent(society -> {
society.setName(societyUpdate.getName());
societyRepo.save(soc);
});
Note: I changed society.getName
to societyUpdate.getName
assuming it was a typo on your side.