【发布时间】:2019-04-27 07:11:01
【问题描述】:
我有 mysql 表,并且有一列使用了 json 数据类型。我想以列作为条件执行查询 使用 JPQL,我可以使用 EntityManager 像下面这样编写它。
它完全适用于以下(选择所有产品)
Query query = em.createQuery("select o from Product o");
并且不适用于 json_extract 函数 + 实体管理器
Query query = em.createQuery("select o from Product o where json_extract(o.des,'$.org') = 'ABC'");
这对我完全不起作用并返回错误
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing [select o from Product o where json_extract(o.des,'$.org') = 'ABC'].
[41, 85] The expression is not a valid conditional expression.
Caused by: org.eclipse.persistence.exceptions.JPQLException:
Exception Description: Syntax error parsing [select o from Product o where json_extract(o.des,'$.org') = 'ABC'].
[41, 85] The expression is not a valid conditional expression.
然后,我尝试了 CrudRepository 并且成功了,但我需要使用 EntityManager 而不是使用 CrudRepository
public interface ProductRepository extends CrudRepository<Product, String> {
@Query(value = "select o from Product o where json_extract(o.des,'$.org') = :org")
List<Product> findProdcutsByOrgJPQL(@Param("org") String org);
}
所以,我的 JPQL 没有问题。 EntityManager 的问题。
如何使用 EntityManager 为 JSON_EXTRACT 函数创建 JPQL 查询
【问题讨论】:
-
“不工作”意味着 JPQL 文档没有具有该名称的此类功能,因此发生错误也就不足为奇了。如果您想将随机 SQL 函数插入 JPQL,那么您可以按照所有 JPA 文档告诉您的那样使用
FUNCTION(...)。换句话说,阅读文档 -
我找到了解决方案。查询 query = em.createQuery("select o from Product o FUNCTION('JSON_EXTRACT', o.des, '$.org') = :org");
标签: mysql jpa spring-data-jpa spring-data jpql