最近在使用Hibernate + JPA做update,希望使用JPA的返回值看到一共有多少条数据被修改,我使用了如下代码进行操作:
持久层代码:
@Modifying(clearAutomatically=true, flushAutomatically = true)
@Transactional
@Query(value = "UPDATE users set enabled = :enabled WHERE id IN :ids", nativeQuery = true)
int batchUpdateUserEnableStatus(@Param("ids") List<Long> ids, @Param("enabled") boolean enabled);
Service层代码:
System.out.println(userRepo.batchUpdateUserEnableStatus(Arrays.asList(1L, 2L, 3L), false));
但当我以一组id作为参数传入时,发现它的返回值是在DB中根据where语句找到的数据行数而非真实修改的数据行数。在上面的例子中,由于这组id中已经有部分的enabled状态已经为false,我只想得到真正修改了多少行数据,怎么办呢?
经过多方查找,找到了2种解决方案:
第一种:全局配置修改,在mysql配置中增加一个参数 useAffectedRows=true
如:
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&rewriteBatchedStatements=true&useAffectedRows=true
spring.datasource.username=root
spring.datasource.password=123456
第二种:修改SQL,增加where条件
@Modifying(clearAutomatically=true, flushAutomatically = true)
@Transactional
@Query(value = "UPDATE users set enabled = :enabled WHERE id IN :ids AND enabled != :enabled", nativeQuery = true)
int batchUpdateUserEnableStatus(@Param("ids") List<Long> ids, @Param("enabled") boolean enabled);