SpringBoot: Couchbase and the _class attribute

Table of contents
Reading Time: 2 minutes

While learning new technology, we often face some barriers. Though this solvable or non-solvable barrier always ends up in making you learn some new things about the technology. A few days back while using Couchbase as my back-end DB in a Spring-boot Application , I encountered one problem.
So, this blog will brief you with the problem and solution.


I have created a reactive Spring-boot application using reactive couchbase API. I have a use case of searching employee by its name. So, I have created a derivable query method.

Mono<Employee> findByEmpName(String name);

But sometimes, it was returning employee details or sometimes an empty response. Though the document was available in the bucket.


Basically, we come up with the observation that whenever we try to add any document in our bucket, a field _class always get added as a part of JSON in a document. So, my bucket is having two types of document one with _class attribute and another without the _class attribute.
And based on the method findByEmpName mentioned above, the auto-generated query would look like :

WHERE (empName= name and _class = "edu.knoldus.employee.model.Employee")

It’s just like if your document consists _class, then it will deserialize the document, otherwise, you will get an empty response.

So, what we can do is, we can overwrite this auto-generated query. Now the question is how? 🤔


We can use the @Query annotation and overwrite our auto-generated query. Let’s see how.

  @Query("#{#n1ql.selectEntity} where empName = $1")
    Mono<Employee> findByEmpName(String name);

Here,  #{#n1ql.selectEntity} is syntactic sugar for select * from bucket which fetches all the employee details by empName from couchbase.
And make sure not to add #{#n1ql.filter} in your query as it filters the document by _class field.
Hope you understand the above use case. Please feel free to comment below if you have any doubt or suggestions.