如何替换 JPQL @Query 中的字符

问题描述

我的数据库一个表 RESOURCE,如:

ID   NAME
1    some_resource
2    another_resource

和部门

ID   NAME    RESOURCE_NAME
1    dep1    some-resource
2    dep2    another-resource

我需要能够在查询中按资源名称匹配它们,为此我希望使用 sql Server 函数 REPLACE:

@Query("select res from Resource res where res.name in " +
            "(select FUNCTION('REPLACE',dep.resourceName,'-','_') from Department dep)")
    Page<Resource> findByAll(Pageable pageable);

但是这会引发异常:

Caused by: org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode 
 \-[METHOD_CALL] MethodNode: 'FUNCTION (REPLACE)'
    +-[METHOD_NAME] IdentNode: 'REPLACE' {originalText=REPLACE}

解决方法

您还需要在 Hibernate 中注册标准 SQL 函数,如下所示:

public class MySQLServerDialect extends SQLServerDialect {
    public SQLServerDialect() {
        super();
        registerFunction("REPLACE",new StandardSQLFunction("REPLACE"));
    }
}