Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of nested object of postgres jsonb column in spring boot

I have used vlad mihalcea's dependency to store json value in table.

Table name: valuation_report JsonbColumn is parameters attribute name in pojo is params

Able to get value of single object like address="Address1"

{"address":"Address1","nestedObj":{"firstName":"Sanjay"}}

To get address I've implemented specification and @Overriden Predicate method like

@Override
public Predicate toPredicate(Root<ValuationReport> root, CriteriaQuery<?> query, CriteriaBuilder cb)
{
return cb.equal(cb.function("jsonb_extract_path_text", String.class,root.<String>.get("params"),cb.literal(this.locale)), this.fieldToSearch);
}

But now i want to find value of NestedObj like nestedObj's firstName is Sanjay.

{"nestedObj":{"firstName":"Sanjay"}}

Please help me😅 And I've written all this with my mobile so sorry for bad format of question😅.

like image 592
Sanjay Sahani Avatar asked Jan 26 '23 08:01

Sanjay Sahani


2 Answers

I have done this with @Query annotation but there's still a way to do with criteria also. I will show my query to do this

@Query(value = "select vr FROM ValuationReport vr  where jsonb_extract_path_text(vr.params,:subParam ,:key)=:value")
    List<ValuationReportJSON> getEntities(@Param("subParam") String subParam,@Param("key") String key,@Param("value") String value);

Hope this works.

like image 144
Harshad Avatar answered Jan 27 '23 21:01

Harshad


Here is your JPA specification.

public Specification<ValuationReport> getFirstNameSpecification(
  final String param, final String subParam, final String value) {
return (root, query, cb) ->
    cb.equal(
        cb.function(
            "jsonb_extract_path_text",
            String.class,
            root.get("params"),
            cb.literal(param),
            cb.literal(subParam)),
        value);
}

Thanks

like image 22
Rahul Gupta Avatar answered Jan 27 '23 21:01

Rahul Gupta