在 HQL 中使用 MAX 删除查询

Delete query with MAX in HQL

我试过用几乎所有的HQL字符串来删除,我找不到问题出在哪里。我最后一次尝试是:

    final String deleteString = "delete Foo l where l.id < (max(id) from l)";

    final Query query = this.getEntityManager().createQuery(deleteString);

    final int deleted = query.executeUpdate();

我得到这个:

org.hibernate.hql.ast.QuerySyntaxException: unexpected token: from near line 1, column 73 [delete eu.unicorn.ctds.entity.Foo l where l.id < (max(id) from l)

问题出在哪里?

最大值前缺少 select。试试这个

final String deleteString = "delete Foo l where l.id < ( select max(id) from l)";

如上更正查询后,执行时会出现另一个错误 "you can't specify target table 'Foo' for update/delete in FROM clause" 这意味着您无法在 select 从同一个 table Foo 中删除 Foo 中的行。所以你必须做2个查询。首先查询 select 最大 ID 并在删除查询中使用该 ID。