温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何解决SpringBoot-JPA删除不成功只执行了查询语句问题

发布时间:2021-12-03 13:35:35 来源:亿速云 阅读:796 作者:小新 栏目:开发技术

这篇文章主要介绍了如何解决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);

测试一遍,删除成功。

感谢你能够认真阅读完这篇文章,希望小编分享的“如何解决SpringBoot-JPA删除不成功只执行了查询语句问题”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI