0

我正在尝试运行包含ltree函数和运算符的 PostgreSQL 本机查询。

这是定义:

@NamedNativeQuery(
            name = "pathSegmentQuery",
            query = "select ltree2text(okm_path) as okm_path, " +
                    "       index(okm_path, text2ltree(:lastSegment)) + 2 <> nlevel(okm_path) as haschild, " +
                    "       case " +
                    "         when index(okm_path, text2ltree(:lastSegment)) + 1 <> nlevel(okm_path) " +
                    "                 then ltree2text(subpath(okm_path, index(okm_path, text2ltree(:lastSegment)) + 1, 1)) " +
                    "           end as child " +
                    "from document " +
                    "where okm_path ~ :pathLike " +
                    "and " +
                    "index(okm_path, text2ltree(:path)) + 1 <> nlevel(okm_path) ",
            resultSetMapping = "pathSegmentQueryRSMapping")

像这样调用:

public List<PathSegment> getPathChildren(String path, String lastSegment) {
    Query query = entityManager.createNamedQuery("pathSegmentQuery");
    String pathLike = "'*." + path + ".*'";

    query.setParameter("path", path);
    query.setParameter("pathLike", pathLike);
    query.setParameter("lastSegment", lastSegment);

    return query.getResultList();
}

结果是错误ERROR: operator does not exist: ltree ~ character varying

当我尝试直接针对数据库运行查询时,它运行正常:

select ltree2text(okm_path) as okm_path,
   index(okm_path, text2ltree('_root_')) + 2 <> nlevel(okm_path) as haschild,
   case
     when index(okm_path, text2ltree('_root_')) + 1 <> nlevel(okm_path)
             then ltree2text(subpath(okm_path, index(okm_path, text2ltree('_root_')) + 1, 1))
       end as child
from document
where
    okm_path ~ '*._root_.*'
and
    index(okm_path, text2ltree('_root_')) + 1 <> nlevel(okm_path)

从错误中可以明显看出 hibernate(?) 不喜欢 th 运算符右侧的类型~,但是正如您所看到的,我在后面的查询中使用了该字符串并且工作正常。

那么我需要对休眠查询做什么才能成功运行查询呢?

编辑:当我替换我时okm_path ~ :pathLike"where okm_path ~ '*._root_.*' "我会得到:

org.postgresql.util.PSQLException: ERROR: syntax error at position 0错误

休眠:5.2.9.Final

PostgreSQL:9.2.23

4

2 回答 2

3

事实证明,lquery()当您对 lquery 进行操作时,需要调用某个函数。

所以我的查询转化为

...
where okm_path ~ lquery(:pathLike)
...

这解决了问题

于 2018-12-27T21:27:54.273 回答
0

错误

operator does not exist: ltree ~ character varying

应该读作

operator does not exist: <left_data_type> <operator> <right_data_type> varying

这意味着没有为这些数据类型定义运算符。例如,当运算符的左侧是整数而右侧是 varchar 时,就会发生这种情况,错误时间为ERROR: operator does not exist: integer = character varying.

这里的问题是当您设置右侧的值时,

query.setParameter("pathLike", pathLike) 

pathLike是一个字符串。所以 Postgres 认为这是将 ltree 与字符串进行比较。当您直接执行 SQL 时,右侧被视为 ltree 表达式而不是字符串。

我不确定这是否可行,但你可以尝试 ltree 可以直接转换为 varchar,但你可以试试这个吗?:

query.setParameter("pathLike", pathLike, Hibernate.OBJECT)

另请参见JDBC 中的 Java 类型到 Postgres ltree

于 2018-12-26T15:11:22.960 回答