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);
}
最新文章
- xml
- Class对象即反射
- C语言--scanf
- ecshop 订单-》订单状态
- IsNullOrEmpty与IsNullOrWhiteSpace区别
- SQL Server占用内存的认识
- Number类型方法
- UNIX 高手的 20 个习惯[转]
- [转] Js获取 本周、本月、本季度、本年、上月、上周、上季度、去年时间段
- EF中使用数据库的标量值函数
- 9.27 noip模拟试题
- 201521123055 《Java程序设计》第7周学习总结
- Nuxt.js学习
- vue实例相关2
- Python中字符串、列表、元组、字典、集合常用方法总结
- [转]REMOTE_ADDR,HTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR
- oracle sql 获取本季度所有月份,上季度所有月份
- 【bzoj3438】 小M的作物
- aruba 802.11ac协议
- http接口自动化测试框架实现
热门文章
- [flask]jina2处理表单--实现搜索功能
- 【SVN】更新提交失败---- Previous operation has not finished; run &#39;cleanup&#39; if it was interrupted解决方法
- WebApi使用二进制方式上传和下载文件
- 安装kafka 记录
- word2vec高效训练方法
- Metinfo3.0 /include/common.inc.php PHP代码注入
- 基于vant实现一个问卷调查
- 关于Eclipse及JDK安装过程中的一些问题
- mac os cmake安装
- Luogu P1450 [HAOI2008]硬币购物