您好,登錄后才能下訂單哦!
這篇文章主要介紹了如何解決SpringBoot-JPA刪除不成功只執行了查詢語句問題,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
使用JPA自定義了一個刪除方法deleteByUserIdAndCommentId發現并沒有刪除掉對應的數據,只執行了查詢語句
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即可
再次執行時會正常執行
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=?
今天寫新模塊的一個刪除功能,測試的時候出了幾個問題。
原代碼:
@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);
于是乎我把該hql語句轉成sql語句去navicat上執行了一遍,報錯顯示sql語法有誤。
根據指示的錯誤起始位置,懷疑是別名問題,查了一下,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);
這下看起來沒問題了,測試了一遍又報錯了。
復制報錯信息又去查了一下,發現對于執行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);
測試一遍,刪除成功。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何解決SpringBoot-JPA刪除不成功只執行了查詢語句問題”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。