• 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);
    }
    

      

  • 相关阅读:
    javascript零散要点收集
    javascript闭包,arguments和prototype
    javascript面向对象规则汇总以及json
    递归转非递归的编程思想
    汇编要点汇总
    队列相关算法
    深度优先遍历算法
    C++面向对象要点
    堆排序
    快速排序算法
  • 原文地址:https://www.cnblogs.com/Andrew520/p/9408469.html
Copyright © 2020-2023  润新知