Spring 数据(或 JPA) - 如何更新实体,但如果不存在,则不插入



我有一种情况,我需要能够更新一个实体,但如果它不存在,就可以抛出异常。

我能想到的最好的:

if (!authorRepository.existsById(1L)) {
throw new Exception("entity doesn't exist yet!");
} else {
authorRepository.save(entity);
}

还有其他方法吗?JPA似乎并没有提供只进行更新的方法,EntityManager.merge((的行为类似于创建或更新。

Save方法在春季启动休眠时自动检测,并检查实体的id是否存在,更新它

最新更新