我有一种情况,我需要能够更新一个实体,但如果它不存在,我需要能够抛出一个异常。
我能想到的最好的办法是:
if (!authorRepository.existsById(1L)) {
throw new Exception("entity doesn't exist yet!");
} else {
authorRepository.save(entity);
}
有没有其他的方法?JPA似乎并没有提供一种只进行更新的方法,EntityManager.merge()的行为类似于create或update。
1条答案
按热度按时间kx7yvsdv1#
保存方法是在Spring Boot 休眠时自动检测并检查实体的id是否已存在,更新它