QueryDSL数组重叠子查询功能

问题描述 投票:0回答:1

具有一个带有jsonb列的表,该列除其他内容之外还包含objectsarray至少一个参数:

SELECT uuid, data FROM product p
WHERE arrayoverlap(array(SELECT jsonb_array_elements(data->'codes')->>'value'), array['57060279', '57627120']);

数据看起来像这样:

{"name": "Peppermint", "codes": [{"type": "EAN-8", "value": "57627120"}, {"type": "EAN-8", "value": "57060279"}], "number": "000000000000002136"]}
{"name": "AnotherNameForPeppermint", "codes": [{"type": "EAN-8", "value": "57060279"}], "number": "000000000000009571"}

是否有使用QueryDSL来运行它们的方法?到目前为止,我已经设法运行了一些基本功能,这些功能允许我匹配单个值,但是对于数组,我不知道如何操作。

import com.querydsl.core.types.Expression;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.ComparablePath;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.core.types.dsl.StringExpression;

import static com.querydsl.core.types.dsl.Expressions.booleanTemplate;
import static com.querydsl.core.types.dsl.Expressions.stringTemplate;

public class QuerydslUtil {
    public static BooleanExpression jsonbContains(StringExpression haystack, Expression<String> needle) {
        return booleanTemplate("FUNCTION('jsonb_contains', {0}, {1}) = true", haystack, needle);
    }

    public static StringExpression jsonbExtractPath(Object data, String propertyName) {
        return getStringExpression("jsonb_extract_path", data, propertyName);
    }

    public static StringExpression jsonbExtractPathText(Object data, String propertyName) {
        return getStringExpression("jsonb_extract_path_text", data, propertyName);
    }

    public static StringExpression getStringExpression(String function, Object data, String propertyName) {
        return stringTemplate("FUNCTION('" + function + "', {0}, {1})", data, propertyName);
    }
}
arrays postgresql jpa querydsl
1个回答
0
投票

找到一种方法:新的辅助方法:

public class QuerydslUtil {
    public static BooleanExpression jsonbExistsAny(StringExpression arrayProperty, StringExpression array) {
        return booleanTemplate("FUNCTION('jsonb_exists_any', {0}, {1}) = true", arrayProperty, array);
    }

    public static BooleanExpression jsonbExistsAny(StringExpression arrayProperty, Collection<?> array) {
        String string = array.stream().map(Object::toString).collect(joining(","));
        return jsonbExistsAny(arrayProperty, stringToArray(string));
    }

    public static StringExpression stringToArray(String string) {
        return stringTemplate("FUNCTION('string_to_array', {0}, {1})", constant(string), constant(","));
    }
}

然后:

StringExpression codesPath = jsonbExtractPath($.data, "codes");
StringExpression codesValues = jsonbExtractPathText(codesPath, "value");
// executor is a Spring Data QuerydslPredicateExecutor
// codes is a Set<String>
Iterable<Product> products = executor.findAll(jsonbExistsAny(codesValues , codes));
© www.soinside.com 2019 - 2024. All rights reserved.