Hibernate的HQL中delete语句中,表是没有别名的,即使你添加了,它也会帮你去掉的

但是这里遇到了一个bug,我的delete语句中包含了一个子查询后,就不对了

 

我的HQL如下:

delete from table1 where column1=:column1 and column2 not in (select column from table2) and column2 not in (:column2)

Hibernate生成的SQL如下:

delete from table1 where column1=? and (column2 not in  (select table2_.column from table2 table2_)) and (table1_.column2 not in  (? , ? , ?))

 

后面的table1_.column2自动添加了一个没有定义的表别名,执行的时候就报错了,最后发现就是因为前面的子查询问题

应该是Hibernate的一个bug,可能是因为检测到了前面的selete后,就自动给后面加上了一个别名,以为这是一个查询语句而不是delete语句了

 

解决方法把两个条件换个顺序就好了

修改后的HQL如下:

delete from table1 where column1=:column1 and column2 not in (:column2) and column2 not in (select column from table2)

这样问题就解决了