菜鳥學習,不對之處,還請糾正。
需要批量更新數據庫的某些數據,項目使用的是JPA,剛對mybatis熟悉一點,又換成了JPA。。。
有點懵。
查詢了一番之后,發現可以使用
In findByIdIn(Collection<?> c) where id in (?)
試驗了一下,可以滿足我的需求。先貼代碼
package com.yd.lipstick.dao.write;
import com.yd.lipstick.entity.Position;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
@Repository
public interface PositionWriteDao extends JpaRepository<Position,Long> {
// @Modifying
// @Transactional
// @Query(value = "update Position p set p.status=2 where p.deviceId=?1 and p.positionId in (?2)")
// int update(String deviceId, Collection<String> collection);
@Modifying
@Transactional
@Query(value = "update Position p set p.status=2 where p.deviceId=:deviceId and p.positionId in (:collection)")
int update(@Param("deviceId") String deviceId, @Param("collection") Collection<String> 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操作。
參考自https://www.cnblogs.com/zhaobingqing/p/6864223.html
https://blog.csdn.net/java_ying/article/details/80511452
---------------------
原文:https://blog.csdn.net/jdd92/article/details/81533353