簡體   English   中英

使用標准 API 搜索 jsonb 字段

[英]Search jsonb field using criteria API

我有一個實體,其中有一個 jsonb 類型的內容字段。 復雜的 json 存儲在此字段中。 我需要在這個領域做出選擇。 我使用標准 API。 這樣的查詢有效:

public Predicate getPredicate(){
        Expression<String> function = builder.function("jsonb_extract_path_text",
                String.class,
                root.<String>get("content"), 
                builder.literal("unit"),
                builder.literal("id")
        );
        return builder.like(
                function,
                "%" + value + "%"
        );
}

JSON 看起來像這樣:

{
 "unit":{
   "id":"58bd51815744bf06e001b57b",
   "name":"my name",
   "another":{
     "anotherId":"45545454"
   }
 }
}

問題是 JSON 的搜索條件可能完全不同。 也許有一個搜索: unit.id = 58bd51815744bf06e001b57b 它可能是這樣的: unit.another.anotherId = 45545454 甚至可能是這樣: unit.id = 58bd51815744bf06e001b57bunit.name = "my name"

我以為我可以這樣解決我的問題:

Expression<String> function = builder.function("jsonb_extract_path_text",
        String.class,
        root.<String>get("content"),
        builder.literal("$.unit.id")
);

但由於某種原因,這不起作用。 任何想法如何解決這一問題?

我找到了一個解決方案:所以我使用 Spring 數據進行搜索

EntityAbstract one = entityRepository.findOne(((Specification<EntityAbstract>)
        (root, query, builder) -> {
            Expression<?>[] expressions = {root.<String>get("content"), builder.literal("unit"), builder.literal("id")};
            return toPredicate(root, query, builder, projectionName, expressions);
        }
)).orElseThrow(() -> new ResourceNotFoundException("Entity not found"));

這就是 Criteria Builder 的方法的樣子

public Predicate toPredicate(Root<EntityAbstract> root, CriteriaQuery<?> query, CriteriaBuilder builder, String value, Expression<?>[] args) {
    Expression<String> function = builder.function("jsonb_extract_path_text",
            String.class, args
    );
    return builder.like(
            function,
            "%" + value + "%"
    );
}

也就是說,我需要形成一個所需長度的數組(表達式),這並不難

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM