如何使用EntityManager为MySql JSON_EXTRACT函数创建JPQL查询

Din*_*esh 2 mysql jpa jpql spring-data spring-data-jpa

我有 mysql 表,有一列使用json 数据类型我想使用JPQL来执行以列作为条件的查询,我可以使用 EntityManager 像下面这样编写它。

它完全适用于以下(选择所有产品)

 Query query = em.createQuery("select o from Product o"); 
Run Code Online (Sandbox Code Playgroud)

并且不适用于 json_extract 函数 + 实体管理器

 Query query = em.createQuery("select o from Product o where json_extract(o.des,'$.org') = 'ABC'");
Run Code Online (Sandbox Code Playgroud)

这对我来说完全不起作用并返回以下错误

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.
Run Code Online (Sandbox Code Playgroud)

然后,我尝试了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);
}
Run Code Online (Sandbox Code Playgroud)

所以,我的JPQL没有问题。EntityManager的问题。

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

Dhe*_*rik 5

正如比利所说:

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

我找到了解决方案:

Query query = em.createQuery("select o from Product o WHERE FUNCTION('JSON_EXTRACT', o.des, '$.org') = :org");
Run Code Online (Sandbox Code Playgroud)