spring data jpa 更新和删除

转自:https://docs.spring.io/spring-data/jpa/docs/2.0.9.RELEASE/reference/html/#repositories.create-instances.spring

1.repository自带的save方法

Saving an entity can be performed with the CrudRepository.save(…) method. It persists or merges the given entity by using the underlying JPA EntityManager. If the entity has not yet been persisted, Spring Data JPA saves the entity with a call to the entityManager.persist(…) method. Otherwise, it calls the entityManager.merge(…) method.

2.query 来更新

@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);

Doing so triggers the query annotated to the method as an updating query instead of a selecting one. As the EntityManagermight contain outdated entities after the execution of the modifying query, we do not automatically clear it (see the JavaDoc of EntityManager.clear() for details), since this effectively drops all non-flushed changes still pending in the EntityManager. If you wish the EntityManager to be cleared automatically, you can set the @Modifying annotation’s clearAutomatically attribute to true.

不大理解的话,百度下clearAutomatically  注解, 参考:https://www.cnblogs.com/xjz1842/p/7217393.html

意思就是说如果加这个注解,就是更新后立刻刷到数据库了。如果是同一方法内,再去查询数据库也是能获取到最新的信息。

不加这个注解,这个方法走完,事务提交了(自己推测的),这个时候才会查询到修改后的,如果是方法没走完,再查数据库还是旧的。

加这个可能会影响性能,所以可能默认的就没加(自己推测的)。碰到上面的情况也没所谓,不用查数据库,直接用修改后的对象吧。

3.删除操作两种方式

interface UserRepository extends Repository<User, Long> {

  void deleteByRoleId(long roleId);

  @Modifying
  @Query("delete from User u where user.role.id = ?1")
  void deleteInBulkByRoleId(long roleId);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值