spring使用jpa进行update操作

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

1、调用保存实体的方法

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

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

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

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

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

例:

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

注:

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

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

org.springframework.dao.InvalidDataAccessApiUsageException: Name must not be null or empty!; nested exception is java.lang.IllegalArgumentException: Name must not be null or empty!

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

猜你喜欢

转载自blog.csdn.net/qq_21033663/article/details/71793328