0
votes

How do we build the Spring JPA query and retrieve data for nested Couchbase document values? I am trying to avoid writing a native query and use the JPA method to retrieve data based on keys which are nested 2 levels.

The couchbase document value is of type Company Where employees is a list and tasks is a property under employee which is a List with details as an object

I would like to query multiple documents and retrieve matching records by categoryId.

Extending the Repository Interface to CouchbaseRepository passing Company and the document id. I have tried something like

// finding by Employees-->Tasks-->Details-->CategoryId 
findByEmployeesTasksDetailsCategoryId(Integer id); // Does not work

but does not work

"company": "Xyc",
"employees": {
   "name": "John Smith",
   "age": 24,
   "tasks": [
       {
            "id": 231,
            "date": "05-13-2019"
            "details": {
                    "categoryName": "Software",
                    "categoryId": 12,     
                    "description": "Buy Software"
                    "location": "Plano, Texas"
                    "zip": 75024
                }
            }
        },
       {
            "id": 789,
            "date": "05-14-2019"
            "details": {
                    "categoryName": "Hardware",
                    "categoryId": 17,     
                    "description": "Buy hardware"
                    "location": "Irving, Texas"
                    "zip": 75038
                }
            }
        },
        {
              "id": 456,
              "date": "05-15-2019"
               "details": {
                    "categoryName": "Hardware",
                    "categoryId": 17,     
                    "description": "Buy hardware"
                    "location": "Plano, Texas"
                    "zip": 75024
                 }
        }
    ]
}

I'm looking for JPA method, where I can get the details task or details by categoryId.

Expected output for categoryId 17

[
   {
      "categoryName": "Hardware",
      "categoryId": 17,     
      "description": "Buy keyboard and mouse"
      "location": "Irving, Texas"
      "zip": 75038
   },
   {
      "categoryName": "Hardware",
      "categoryId": 17,     
      "description": "Buy monitor"
      "location": "Plano, Texas"
      "zip": 75024
   }

]
1

1 Answers

1
votes

You can't use Spring Data to query nested entities as it is not part of the original Spring Data specification. However, you can simply write N1QL queries using the @Query annotation

ex:

    @Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and companyId = $1 and " +
        " removed = $2 and lower(name) like $3 order by lower(name) asc LIMIT $4 OFFSET  $5 ")
    List<FamilyResource> listFamilies(String companyId, boolean removed, String name, int limit, int offset);

In your case, you can simply use UNNEST https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/unnest.html