jpa的批量修改_SpringbBoot之JPA批量更新

时间:2025-04-24 07:32:17

菜鸟学习,不对之处,还请纠正。

需要批量更新数据库的某些数据,项目使用的是JPA,刚对mybatis熟悉一点,又换成了JPA。。。

有点懵。

查询了一番之后,发现可以使用

In findByIdIn(Collection> c) where id in (?)

试验了一下,可以满足我的需求。先贴代码

package ;

import ;

import ;

import ;

import ;

import ;

import ;

import ;

import ;

@Repository

public interface PositionWriteDao extends JpaRepository {

// @Modifying

// @Transactional

// @Query(value = "update Position p set =2 where =?1 and in (?2)")

// int update(String deviceId, Collection collection);

@Modifying

@Transactional

@Query(value = "update Position p set =2 where =:deviceId and in (:collection)")

int update(@Param("deviceId") String deviceId, @Param("collection") Collection collection);

}

贴出来的两种update实现的功能是一样的。

第一种使用的是索引参数:索引值从1开始,查询中"?X"个数需要与方法定义的参数个数相一致,并且顺序也要一致。

注释:上面代码中的?1,?2表示参数的占位符,需要和方法中所传递的参数顺序一致。X是从1开始。

第二种使用的是命名参数(推荐使用此方式):可以定义好参数名,赋值时使用@Param("参数名"),而不用管顺序。

注释:上面代码中:devideId ,:collection 表示为参数命名,方法中所传递的参数使用@Param注解标识命名参数。这种方式不用管参数的顺序。

@Modifying注解

1、在@Query注解中编写JPQL实现DELETE和UPDATE操作的时候必须加上@modifying注解,以通知Spring Data 这是一个DELETE或UPDATE操作。

2、UPDATE或者DELETE操作需要使用事务,此时需要 定义Service层,在Service层的方法上添加事务操作。

3、注意JPQL不支持INSERT操作。

参考自/zhaobingqing/p/

/java_ying/article/details/80511452

---------------------

原文:/jdd92/article/details/81533353