我正在Spring Service中编写一个update
方法,它说getOne((不推荐使用,我已经审查了替代方案,findById(long id)
似乎是首选,但我很难让它在我的情况下发挥作用。
我想更新数据库中保存的对象的name
字段。然后我想用更新后的名称将其重新保存在数据库中。
我最初用getOne()
有这个代码
Society inDb = societyRepo.getOne(id);
inDb.setName(societyUpdate.getName());
societyRepo.save(inDb);
我已尝试对此进行如下修改,
Optional<Society> soc = societyRepo.findById(id);
soc.ifPresent(society -> society.setName(society.getName()));
societyRepo.save(soc);
但由于soc
现在是可选的,我无法将其保存回数据库中。
是否可以在SocietyRepoSociety findbyId(long id);
中编写另一个方法,然后允许我使用Society s = societyRepo.findById(id); to get the
Societyfrom the database, update the
name`字段,然后重新保存在数据库中?
假设这一切都发生在一个事务中,实际上不需要调用save
。
如果它不在单个事务中,或者为了清晰起见,您希望保留对save
的调用,则以下操作将起作用:
societyRepo.findById(id)
.ifPresent(society -> {
society.setName(societyUpdate.getName());
societyRepo.save(soc);
});
注意:我把society.getName
改成了societyUpdate.getName
,假设这是你的错别字。
事情可能已经发生了变化https://docs.spring.io/spring-data/data-jpa/docs/current/api/deprecated-list.html截至春季数据jpa 3.0.0…
org.springframework...JpaRepository.getById(ID) use JpaRepository.getReferenceById(ID) instead.
org.springframework...JpaRepository.getOne(ID) use JpaRepository.getReferenceById(ID) instead.
所以getReferenceById似乎是一个枯燥的替代品。