[英]How to update an entity with a condition(where clause) and get the updated entity in method response in spring data jpa
我正在处理并发更新处理的东西,我的场景是 - 可以从 UI 将员工标记为非活动,但如果一旦标记为非活动,则不应再次将其标记为非活动。 我想通过使用 status=active 的条件更新实体进行 db update 调用来实现它。 我需要更新的实体作为回报。
如何使用条件(where 子句)更新实体并在 spring 数据 jpa 中的方法响应中获取更新的实体
employeRepository.save(employee); // is it possible to do something like this with a condition at the same time update method returns updated entity.
您在这里与 JPA 的颗粒背道而驰。
我建议你这样做 JPA 方式:
加载实体
如果status
属性不是inactive
,则将其设置为active
。
当事务结束时,这将被写入数据库。
如果你坚持使用更新语句
您可以使用以下过程:
如果实体是当前 session 的一部分:
使用 SQL 或 JPQL 执行更新,其中带有这样的 where 子句: ... WHERE id =:id and status <> 'inactive'
使用 id 再次加载实体。
您可以使用JPQL 。
uery query = entityManager.createQuery(
"UPDATE employee SET status = \"inactive\"" +
"WHERE status=\"active\"");
query.executeUpdate();
或者只是 spring 数据
@Modifying
@Query("update employee u status = `inactive` where status=`active` and ...")
void disableUsers(...);
然而,处理并发查询的一个好方法可能是乐观锁定和@Version
注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.