工作中看到JPA中有一个@Modifying的用法,故此记录一下
JDK1.8
Springboot2
JPA
Oracle
之前一直用的是这样的写法:
String updateQuery = "UPDATE user SET name = :name WHERE id = :id"; EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Query query = entityManager.createNativeQuery(updateQuery); query.setParameter("name", newName); query.setParameter("id", id); query.executeUpdate(); transaction.commit(); entityManager.close();
或者是这样的写法:
User user = new User(); user.setId(id); user.setName(newName); userRepository.save(user); // userRepository 通过构造器注入
使用@Modifying
@Repository public interface UserRepository extends JpaRepository<User, Long> { @Modifying @Query("update User u set u.name = ?1 where u.id = ?2") void updateUserNameById(String name, Long id); @Modifying @Query(value = "UPDATE users SET name = :name WHERE id = :id", nativeQuery = true) void updateUserNativeQuery(@Param("name") String name, @Param("id") Long id); }
标签:entityManager,name,JPA,Modifying,user,query,注解,id From: https://www.cnblogs.com/onejay/p/17253582.html