spring使用jpa进行update操作

时间:2025-02-21 21:26:41

spring使用jpa进行update操作主要有两种方式:

1、调用保存实体的方法

1)保存一个实体:(T entity)

2)保存多个实体:(Iterable<T> entities)

3)保存并立即刷新一个实体:(T entity)

注:若是更改,entity中必须设置了主键字段,不然不能对应上数据库中的记录,变成新增(数据库自动生成主键)或报错(数据库不自动生成主键)了

2、@Query注解,自己写JPQL语句

例:

@Modifying
@Query("update ShopCoupon sc set = true where in :ids")
public void deleteByIds(@Param(value = "ids") List<String> ids);

注:

1)update或delete时必须使用@Modifying对方法进行注解,才能使得ORM知道现在要执行的是写操作

2)有时候不加@Param注解参数,可能会报如下异常:

: Name must not be null or empty!; nested exception is : Name must not be null or empty!

3)当使用集合作为条件时,可参考此处的ids