Java 如何使用条件(where子句)更新实体,并在SpringDataJPA的方法响应中获取更新的实体

Java 如何使用条件(where子句)更新实体,并在SpringDataJPA的方法响应中获取更新的实体,java,sql,spring-boot,spring-data-jpa,spring-data,Java,Sql,Spring Boot,Spring Data Jpa,Spring Data,我正在处理并发更新处理的东西,我的场景是-员工可以从UI标记为不活动,但如果一旦标记为不活动,就不允许再次标记为不活动。我想通过使用status=active的条件更新实体进行db update调用来实现它。我需要更新的实体作为回报 如何使用条件(where子句)更新实体,并在SpringDataJPA的方法响应中获取更新的实体 employeRepository.save(employee); // is it possible to do something like this with a

我正在处理并发更新处理的东西,我的场景是-员工可以从UI标记为不活动,但如果一旦标记为不活动,就不允许再次标记为不活动。我想通过使用status=active的条件更新实体进行db update调用来实现它。我需要更新的实体作为回报

如何使用条件(where子句)更新实体,并在SpringDataJPA的方法响应中获取更新的实体

employeRepository.save(employee); // is it possible to do something like this with a condition at the same time update method returns updated entity.

您可以使用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
注释

在这里,你的工作与JPA格格不入

我建议您采用JPA的方式:

  • 加载实体

  • 如果
    status
    属性不是
    inactive
    则将其设置为
    active

  • 当事务结束时,这将写入数据库

  • 如果您坚持使用update语句

    您可以使用以下过程:

  • 如果实体是当前会话的一部分:

  • 刷新对数据库的所有更改
  • 从会话中逐出实体
  • 使用SQL或JPQL以及where子句执行更新,如:
    。。。其中id=:id和状态为“非活动”

  • 使用id再次加载实体


  • 我希望更新方法也返回更新的实体。对于您的情况,乐观锁定和
    @Version
    注释可能足够好,然后您可以使用EmployeeRepository.save(employee)。是否可以实现以下操作:不可能,SQL update返回唯一数量的更新行。“修改查询只能使用void或int/Integer作为返回类型”