Spring Data Jpa Spring中getOne(long id)的可行替代方案是什么

shyt4zoc  于 10个月前  发布在  Spring
关注(0)|答案(2)|浏览(143)

我正在Spring Service中编写一个update方法,它说getOne()已被弃用,我已经审查了替代方案,findById(long id)似乎是go to选项,但我正在努力让它在我的情况下工作。
我想更新保存在数据库中的对象的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现在是可选的,我不能将其保存回数据库。
是否可以在SocietyRepo Society findbyId(long id);中编写另一个方法,然后允许我使用Society s = societyRepo.findById(id); to get the Society from the database, update the name`字段,然后重新保存在数据库中?

guz6ccqo

guz6ccqo1#

假设所有这些都发生在一个事务中,实际上不需要调用save
如果它不在单个事务中,或者为了清楚起见,您希望保留对save的调用,则可以执行以下操作:

societyRepo.findById(id)
    .ifPresent(society -> {
        society.setName(societyUpdate.getName());
        societyRepo.save(soc);
    });

注意:我将society.getName更改为societyUpdate.getName,假设这是您这边的错字。

wb1gzix0

wb1gzix02#

事情可能已经过去了。根据spring-data-jpa 3.0.0的https://docs.spring.io/spring-data/data-jpa/docs/current/api/deprecated-list.html...

org.springframework...JpaRepository.getById(ID) use JpaRepository.getReferenceById(ID) instead.

org.springframework...JpaRepository.getOne(ID) use JpaRepository.getReferenceById(ID) instead.

所以getReferenceById似乎是一个直接的替代。

相关问题