In this blog, I am going to share some of my findings regarding CouchbaseTemplate while learning spring-boot.
So, while working with Spring-boot application and couchbase as DB, I just learned the two approaches of writing Repository. The first one is simply declaring the repository interface and extending it with CrudRepository and another approach provided by the Spring context is template based i.e. CouchbaseTemplate which can simply be injected to our class.
So, in this blog, we will discuss how we can create a custom query using CouchbaseTemplate in SpringBoot Application.
What is CouchbaseTemplate?
CouchbaseTemplate is the class for Couchbase database operations which provides the following functionality
1) Inbuilt Methods that directly query the DB.
2) POJO mapping support to and from JSON
3) Inbuilt methods that allow me to create the custom query.
First of all, you have to autowire the Couchbase Template just like below code:
@Autowired private CouchbaseTemplate couchbaseTemplate;
There are plenty of inbuilt methods that directly provided by CouchbaseTemplate. Let’s share some of my learning.
Example: Check whether the document exists or not
Example: Find the document by id
In the above example, the document is mapped to the POJO if found in the DB otherwise it will return null.
Example: Consider a situation where you have to create a custom query and have to fetch empName and empId
The findByN1QL method executes the query and also map the query result to the corresponding POJO and return List<POJO>
Quite easy isn’t it?
But, what looks strange in the above example is that we are also fetching some metadata also like META() .id, META() .cas. If you try to execute the query without fetching the metadata, it will give you the following error
Unable to retrieve enough metadata for N1QL to entity mapping, have you selected _ID and _CAS?
So, these values are required for mapping the key and version fields.
There are also some methods that provide you cluster and bucket info like getCouchbaseClusterInfo(). More than that couchbase template also provides methods like findById(), save(), remove(), etc which we can also get by extending CrudRepository.
Hope this is helpful. Please feel free to provide your suggestions and learning. Happy learning!!