Java 如何使用条件(where子句)更新实体,并在SpringDataJPA的方法响应中获取更新的实体
我正在处理并发更新处理的东西,我的场景是-员工可以从UI标记为不活动,但如果一旦标记为不活动,就不允许再次标记为不活动。我想通过使用status=active的条件更新实体进行db update调用来实现它。我需要更新的实体作为回报 如何使用条件(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
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
。。。其中id=:id和状态为“非活动”
我希望更新方法也返回更新的实体。对于您的情况,乐观锁定和
@Version
注释可能足够好,然后您可以使用EmployeeRepository.save(employee)。是否可以实现以下操作:不可能,SQL update返回唯一数量的更新行。“修改查询只能使用void或int/Integer作为返回类型”