SpringBoot-JPA刪除不成功,只執(zhí)行了查詢語句問題
SpringBoot-JPA刪除不成功,只執(zhí)行了查詢語句
今天使用JPA自定義了一個刪除方法deleteByUserIdAndCommentId發(fā)現(xiàn)并沒有刪除掉對應的數(shù)據(jù),只執(zhí)行了查詢語句
Hibernate: select good0_.id as id1_6_, good0_.commentId as commenti2_6_, good0_.userId as userid3_6_ from tbl_good good0_ where good0_.userId=? and good0_.commentId=?
解決方法
在刪除方法前加注解@Transactional即可
再次執(zhí)行時會正常執(zhí)行
Hibernate: select good0_.id as id1_6_, good0_.commentId as commenti2_6_, good0_.userId as userid3_6_ from tbl_good good0_ where good0_.userId=? and good0_.commentId=? Hibernate: delete from tbl_good where id=? Hibernate: select comment0_.id as id1_3_0_, comment0_.articleId as articlei2_3_0_, comment0_.ccomment as ccomment3_3_0_, comment0_.goodNum as goodnum4_3_0_, comment0_.userId as userid5_3_0_, comment0_.userType as usertype6_3_0_ from tbl_comment comment0_ where comment0_.id=?
JPA中使用delete踩坑記錄
今天寫新模塊的一個刪除功能,測試的時候出了幾個問題。
原代碼:
@Query("delete from PrivateMessageEntity ae " + "where ((ae.sendId=?1 and ae.receiveId=?2)or(ae.sendId=?2 and ae.receiveId=?1)) " + "and ae.deleted=?3") int deleteDetailPrivateLetterList(Long sendId, Long receiveId, Boolean deleted);
測試時報錯,大概是sql有問題
于是乎我把該hql語句轉成sql語句去navicat上執(zhí)行了一遍,報錯顯示sql語法有誤。
根據(jù)指示的錯誤起始位置,懷疑是別名問題,查了一下,sql的delete在使用別名時 在 delete 與from 之間的表別名不可省略
正確sql如下:
delete a.* from tb_table a where a.id=1;
修改之后的代碼如下:
@Query(value = "delete ae.* from tb_zone_private_message ae " + "where ((ae.sendId=?1 and ae.receiveId=?2)or(ae.sendId=?2 and ae.receiveId=?1)) " + "and ae.deleted=?3",nativeQuery = true) int deleteDetailPrivateLetterList(Long sendId, Long receiveId, Boolean deleted);
這下看起來沒問題了,測試了一遍又報錯了。
復制報錯信息又去查了一下,發(fā)現(xiàn)對于執(zhí)行update和delete語句需要添加@Modifying注解。
修改后代碼如下:
@Modifying @Query(value = "delete ae.* from tb_zone_private_message ae " + "where ((ae.sendId=?1 and ae.receiveId=?2)or(ae.sendId=?2 and ae.receiveId=?1)) " + "and ae.deleted=?3",nativeQuery = true) @Transactional int deleteDetailPrivateLetterList(Long sendId, Long receiveId, Boolean deleted);
測試一遍,刪除成功。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
java IO流 之 輸入流 InputString()的使用
這篇文章主要介紹了java IO流 之 輸入流 InputString()的使用,以及讀取數(shù)據(jù)的三種方式詳解,非常不錯,需要的朋友可以參考下2016-12-12Spring Boot整合ElasticSearch實現(xiàn)多版本兼容的方法詳解
簡單說,ElasticSearch(簡稱 ES)是搜索引擎,是結構化數(shù)據(jù)的分布式搜索引擎。下面這篇文章主要給大家介紹了關于Spring Boot整合ElasticSearch實現(xiàn)多版本兼容的相關資料,需要的朋友可以參考借鑒,下面來一起看看吧2018-05-05Springboot @Validated和@Valid的區(qū)別及使用詳解
這篇文章主要介紹了Springboot @Validated和@Valid的區(qū)別及使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05