【问题标题】:Spring Data (or JPA) - How to update entity but don't insert if it doesn't existSpring Data(或 JPA) - 如何更新实体但如果它不存在则不插入
【发布时间】:2022-07-30 14:56:09
【问题描述】:

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

我能想到的最好的:

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

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

【问题讨论】:

标签: hibernate jpa spring-data-jpa spring-data


【解决方案1】:

保存方法是在spring boot hibernate中自动检测并检查实体的id是否存在,更新它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2021-02-04
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多