zoukankan      html  css  js  c++  java
  • 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);
    }
    

      

  • 相关阅读:
    nopCommerce 2.60 之实现产品规格属性分组筛选
    chromedriver的使用
    linux 服务器发现了挖矿病毒
    C++day11 学习笔记
    C++day08 学习笔记
    C++day10 学习笔记
    C++day07 学习笔记
    C++day06 学习笔记
    C++day04 学习笔记
    C++day02 学习笔记
  • 原文地址:https://www.cnblogs.com/Andrew520/p/9408469.html
Copyright © 2011-2022 走看看