【问题标题】:org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected tokenorg.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌
【发布时间】:2016-06-08 00:32:06
【问题描述】:

当我尝试在下面实现我的query 时出现以下错误:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token 

我的查询位于扩展 CrudRepository 的 Spring 数据 PersonRepository

查询:

@Modifying
@Transactional
@Query("DELETE (entity) FROM Person entity WHERE entity.id = :id")
List<Person> deleteFromPersonWithId(@Param("id") String id);

我的语法有什么错误?

【问题讨论】:

  • 应该是 entity.id 代替 where 子句中的 person.id
  • 抱歉打错了,我有 entity.id
  • 好的,你不需要括号中的实体来删除
  • 这样写DELETE FROM Person WHERE id = :id。但最好使用entityManager.remove(entity) 语法,因为这也会删除关联的实例
  • sping中如何创建实体管理器?

标签: java spring list jpa transactional


【解决方案1】:

这样更改您的注释;

@Modifying
@Transactional
@Query("DELETE FROM Person WHERE id = :id")
void deleteFromPersonWithId(@Param("id") String id);

【讨论】:

  • 出现错误:org.hibernate.hql.internal.QueryExecutionRequestException:不支持 DML 操作
  • 可能 hibernate 正在调用 query.list() 语句,因为您试图返回 List,而这在 delete 语句中是不可能的。用 void 替换返回类型。
【解决方案2】:
entityManager.remove(entityInstance)

在事务提交时会从数据库中移除实体。

【讨论】:

    【解决方案3】:

    你没有正确的 DELETE 查询语法,它应该是这样的。

    DELETE FROM Person entity WHERE entity.id = :id
    

    顺便说一句,有一个delete 方法可以完全满足您在CrudRepository 本身中的要求。所以不需要复制它。

    【讨论】:

    • 那么这是原生查询吗?
    • 不,是 JPQL 查询。
    • 只需在该接口的实现实例上调用delete 方法,并将您的实体对象传递给它。那应该做的工作:)
    【解决方案4】:

    查询必须是:

    @Query("DELETE FROM Person entity WHERE entity.id = :id")
    

    【讨论】:

      猜你喜欢
      • 2020-03-13
      • 2020-09-05
      • 2021-08-20
      • 2015-07-12
      • 1970-01-01
      • 2016-02-21
      • 2018-11-16
      • 2018-10-09
      • 1970-01-01
      相关资源
      最近更新 更多