HQL - 检查数组是否包含值

HQL - Check if an Array contains a value

我的第一个实体 Class 中有一个数组字段,如下所示:

class Entity1{
       private Integer col1;
       private String col2;
       private Integer[] col3Arr;
}

我有另一个实体 class 如下:

class Entity2{
       private Integer col1;
       private String col2;
       private Integer col3;
}

我正在通过加入多个其他实体来获取记录,如果 col3Arr 包含来自实体 2 的值 col3,我必须与这些实体一起加入 Entity1

使用 PSQL,我可以通过以下语句轻松实现此目的

//Other part of query
join Entity2 e2 on (//conditions from other joined tables//)
join Entity1 e1 on e2.col3=ANY(e1.col3Arr)

ANY 的 HQL 等价物是什么? 或者在 HQL 中是否有任何其他方法来检查数组是否包含特定值?

根据 hibernate documentation:

When discussing arrays, it is important to understand the distinction between SQL array types and Java arrays that are mapped as part of the application’s domain model.

Not all databases implement the SQL-99 ARRAY type and, for this reason, Hibernate doesn’t support native database array types.

因此,在 HQL 中没有 PSQL ANY 的等价物。

要映射数组,您需要自定义类型。您可以为此使用休眠类型项目:https://vladmihalcea.com/how-to-map-java-and-sql-arrays-with-jpa-and-hibernate/

您尝试使用 e2.col3 = FUNCTION('ANY', e1.col3Arr) 了吗?如果这不起作用,我建议您创建一个自定义 SQLFunction 来呈现您想要的 SQL,例如

public class ArrayAny implements SQLFunction {

    @Override
    public boolean hasArguments() {
        return true;
    }

    @Override
    public boolean hasParenthesesIfNoArguments() {
        return true;
    }

    @Override
    public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
        return firstArgumentType;
    }

    @Override
    public String render(Type firstArgumentType, List args, SessionFactoryImplementor factory) throws QueryException {
        return "any(" + args.get(0) + ")";
    }
}

您必须在方言中注册该函数。