使用ltree本机命名查询休眠

时间:2018-12-26 15:00:20

标签: java postgresql hibernate ltree

我正在尝试运行包含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(?)不喜欢~运算符右侧的类型,但是如您所见,我在稍后的查询中使用了字符串,并且运行良好。

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

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

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

休眠:5.2.9。最终

postgresql:9.2.23

2 个答案:

答案 0 :(得分: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)

另请参阅Java type in JDBC to Postgres ltree

答案 1 :(得分:0)

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

所以我的查询翻译成

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

这可以解决问题