Springboot JPA update语句的返回值

2 篇文章 0 订阅

最近在使用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);

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Spring Data JPA,可以通过编写实体类和仓库接口的方式来进行增删改查操作,具体步骤如下: 1. 在实体类上添加注解@Entity和@Id,指定实体类对应的数据库表和主键字段。 2. 在仓库接口中继承JpaRepository,该接口提供了基本的CRUD操作方法。 3. 在方法上使用JPA自动生成的方法名或自定义方法名,来完成相应的增删改查操作。例如: ```java public interface UserRepository extends JpaRepository<User, Long> { User findByName(String name); List<User> findByAgeGreaterThan(int age); @Modifying @Query("update User set name = ?1 where id = ?2") int updateNameById(String name, Long id); } ``` 上述代码中,UserRepository是继承了JpaRepository的仓库接口,其中定义了三个方法: - findByName:通过用户名查找User对象 - findByAgeGreaterThan:查找年龄大于指定值的User对象列表 - updateNameById:根据id更新用户姓名 其中,updateNameById方法使用了@Modifying和@Query注解,用于指定该方法是一个修改操作,并且使用JPQL语句来更新数据。 4. 在Spring Boot应用中配置JPA相关的属性,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update ``` 上述配置中,指定了数据库连接信息、是否输出SQL语句、表结构自动更新等属性。 使用Spring Data JPA进行增删改查操作,可以简化开发工作,提高开发效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值