SpringBoot-JPA删除不成功,只执行了查询语句问题

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);

测试一遍,删除成功。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持云海天教程。