Custom Repository Implementation in SpringBoot REST API
Hi guys! Have you created Rest APIs using SpringBoot? I think you may have already done it! There are so many ways that developers follow while creating APIs with SpringBoot. But the most common way uses a set of classes that use to build the layered architecture on the API. So, before starting today's tutorial - let me introduce the way that I'm following.
Layers in the API structure:
- controllers - which accept the client requests
- models - which contains entity classes/POJOs
- services - which performs the logic to return data
- repositories - which handles data with database
IMPORTANT:
For this tutorial, we need the below dependencies. So, create a SpringBoot project with the below dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
What are repositories?
Repositories are the place where we deal with databases. I will use MongoDB as my DBMS in this tutorial. It's the easiest database to setup in SpringBoot. Inside resources/application.properties file, we need to place this configuration. Database name is ProductDB.
spring.data.mongodb.uri=mongodb://localhost:27017/ProductDB
Collection name is products. You can see it in POJO class.
Normally we can inherit the basic functionalities from MongoRepository which are needed when data is manipulated. The below screenshot will show you the basic functionalities that MongoRepository provides us.
So let me show you a simple repository created for a Pojo called Product. It only has 3 properties such as id, name, and description. This repository should be an interface.
NOTE:
ID has been taken as a Long data type value. That's why Long is there in the inheritance(extends) code block.
This is the Product Pojo class. The collection has been set as products.
How to use Repository?
So in our service layer, we can use the repository by auto wiring it into the service.
@Autowired
private ProductRepository productRepository;
The functionalities I have shown you in the above screenshot are available to be used with Product POJO, here. Let me show you an example in the service layer.
@Override
public Product getProductById(long productId) {
Optional<Product> product = this.productRepository.findById(productId);
if (product.isPresent()) {
return product.get();
} else {
throw new RuntimeException(
"Product not found with id: " + productId
);
}
}
So, we have used findById method to get the product when its ID is given.
How to add custom functionalities?
You can see our repository only has the functions available with MongoRepository. What should we do if we need to set up a method to find the product by its name? or description? Currently, we only have the ability to deal with the ID of the products. This is the tricky part of this article also.
Here we have to define another interface called ProductRepositoryCustom.
NOTE:
Remember!!! You MUST follow this convention
RepoName + "Custom" => ProductRepositoryCustom
Let's include a method called findByName in this interface. That is responsible for searching for products by their names!
This is only an interface. Right? So, where is the implementation of this method???
So, here we need another class called ProductRepositoryImpl. That implements the custom repository we created(ProductRepositoryCustom).
NOTE:
Remember!!! You MUST follow this naming convention
RepoName + "Impl" => ProductRepositoryImpl
Let's discuss this method implementation.
MongoTemplate is a Java class come with org.springframework.data.mongodb.core dependency. It contains a set of methods that can be used with Mongo data manipulations. We have to get it through dependency injection, into the custom repository.
Query is also coming from the above-mentioned dependency. It can define queries with a set of criteria. Here, I have set the query to get the name by a where clause and making it equal to the given name.
Query query = new Query().addCriteria(Criteria.where("name").is(name));
Like this, you can play a lot with Query class to perform so many different mongo queries.
Then mongoTemplate.find() is called with this custom query object to get the matching DB records from products collection.
Now we are ready to use our custom repository method named as findByname!
Integrate Custom Repository
We have just finished the implementation of the custom repository. But if we need to use its methods, we have to wire it into the existing setup. Where to plug it? It should be plugged into our main Repository interface class which was extended by MongoRepository. Look at the below code. I have used multiple inheritance with interfaces here.
Now custom repository has been plugged and ready to use!!!
Let me show you how these classes are connected finally using a UML class diagram!
In our service layer, we can use this method as follows.
@Override
public List<Product> getProductByName(String productName) {
Optional<List<Product>> products = this.productRepository.findByName(
productName
);
if (products.isPresent()) {
List<Product> productList = products.get();
if (productList.size() > 0) {
return productList;
} else {
throw new RuntimeException(
"Product not found with name: " + productName
);
}
} else {
throw new RuntimeException(
"Product not found with name: " + productName
);
}
}
So, here's the result we get for this API when it is called from POSTMAN.
NOTE:
I have not included the controller layer here. Normally the controller talks to the service and then the service talks to the repository to fetch and return data.
That's it, guys!!! Products can be retrieved by name now...
You can define methods as you need with this custom repository implementation!
Ho[e you got some knowledge from this. Keep in touch with me for more tips on SpringBoot implementations...
Good Bye!
15 Comments
Nice Post..
ReplyDeletepersonal loan
loan app
Very Nice Post,
ReplyDeleteThis is very informative blog thanks for sharing this blog.
ReplyDeletecovert jpg to pdf
convert pdf to png
This comment has been removed by the author.
ReplyDeleteNice Blog..
ReplyDeleteinstagram video downloader
very informative blog thanks for sharing such a nice information
ReplyDeleteSuccessfulltime
This comment has been removed by the author.
ReplyDeleteOnline-MBA
ReplyDeleteOnline-MBA-in-Sports-Management
Online-MBA-in-General-Management
Thanks for sharing this blog... I really like it. This blog is so informative. If you want to learn about theBest Mediclaim Policy, you can visit nivabhupa.
ReplyDeletebest health insurance plans in india
best health insurance in india
Top BCom Hon Collages in India The Bachelor of Commerce Honours (BCom Hons.) program is a prestigious undergraduate degree that offers specialized education in various fields of commerce, providing students with in-depth knowledge and skills essential for pursuing careers in business, finance, and related sectors. In this comprehensive guide, we will delve into various aspects of the BCom Hons. program, including its structure, admission process, eligibility criteria, and curriculum.
ReplyDeleteI really loved your blog post, it was so informative and I learned so much from you .
ReplyDeleteThanks for sharing valuable information with us
Ansa Training - Best Autocad Cadd ANSA Training in Chennai
Get top-notch Law assignment help from qualified experts. We offer personalized support to enhance your understanding and improve your grades in legal coursework.
ReplyDelete11Xplay is your go-to platform for an unparalleled online gaming experience, offering sports betting and casino games designed specifically for Indian players. Enjoy live sports betting, favorite games such as Teen Patti and Rummy, along with fast, secure payments and instant withdrawals. The platform boasts a user-friendly interface and 24/7 customer support to ensure a hassle-free experience. Explore other top-notch platforms like Lotusbhai and Betbook250 to elevate your gaming journey to the next level!
ReplyDeleteWelcome to 1xbet – your trusted gateway to 1xBet’s world of gaming and entertainment. We provide a seamless, secure login experience for users to access live sports, casino games, and global events with ease.
ReplyDeleteSatsport is your ultimate destination for cutting-edge sports insights and services in India. Offering a seamless platform for sports enthusiasts, we specialize in delivering real-time updates, secure transactions, and an unmatched user experience. Discover the best of sports engagement with Satsports today!"
ReplyDelete