首页 > 解决方案 > 如何使用 EntityManager 为 MySql JSON_EXTRACT 函数创建 JPQL 查询

问题描述

我有 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的问题。

如何使用EntityManagerJSON_EXTRACT函数创建JPQL 查询

标签: mysqljpaspring-data-jpaspring-datajpql

解决方案


正如比利所说:

JPQL 文档没有具有该名称的此类功能,因此发生错误也就不足为奇了。如果您想将随机 SQL 函数插入 JPQL,那么您可以按照所有 JPA 文档告诉您的那样使用 FUNCTION(...)

我找到了解决方案:

Query query = em.createQuery("select o from Product o FUNCTION('JSON_EXTRACT', o.des, '$.org') = :org");

推荐阅读