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

      

  • 相关阅读:
    HDU 1455 http://acm.hdu.edu.cn/showproblem.php?pid=1455
    UVA 11300 Spreading the Wealth
    HDU 1702 http://acm.hdu.edu.cn/showproblem.php?pid=1702
    栈的简单应用 HDU 1022 http://acm.hdu.edu.cn/showproblem.php?pid=1022
    HDU 1702 队列与栈的简单运用http://acm.hdu.edu.cn/showproblem.php?pid=1702
    背包模板(01背包,完全背包,多重背包)
    XSS内容拓展--伪造你的IP
    Linux文件系统
    2015阿里校招研发工程师笔试题
    鸟哥的私房菜复习一
  • 原文地址:https://www.cnblogs.com/Andrew520/p/9408469.html
Copyright © 2011-2022 走看看