SpringBoot-JPA刪除不成功,隻執行瞭查詢語句問題

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=?

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上執行瞭一遍,報錯顯示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);

測試一遍,刪除成功。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: