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 {

  void deleteByRoleId(long roleId);

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

 

你可能感兴趣的:(spring,data,jpa)