jpa 自定義sql 刪除方法注意點


1、jpa自帶的delete()方法可以成功刪除對象

delete(id),或者delete(entity)

2、自定義刪除方法注意點

參考:https://www.jianshu.com/p/9d5bf0e4943f

 @RequestMapping(value = "/delById")
    public void delById(@RequestParam("id") int userId){
       accountDao.delAccount(userId);
    }

  注意,采用可以看到我們的@Query注解好像只是用來查詢的,但是如果配合@Modifying注解一共使用,則可以完成數據的刪除、添加、更新操作

public interface AccountDao  extends JpaRepository<Account,Integer> {

   // @Transactional
    @Modifying
    @Query(value = "delete from Account where id =?1",nativeQuery = true)
    void delAccount(int id);
}

  可以看到報TransactionRequiredException

javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:54) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:238) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.1.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.13.1.RELEASE.jar:na]

 

在對應的方法上添加@Transactional 刪除成功

public interface AccountDao  extends JpaRepository<Account,Integer> {

    @Transactional
    @Modifying
    @Query(value = "delete from Account where id =?1",nativeQuery = true)
    void delAccount(int id);
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM