springboot, java, custom repository, 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.

mongo repostory, springboot

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!

custom repository, springboot



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.

springboot, rest-api, postman


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!






10 Comments

  1. This is very informative blog thanks for sharing this blog.

    covert jpg to pdf
    convert pdf to png

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. very informative blog thanks for sharing such a nice information
    Successfulltime

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Online-MBA
    Online-MBA-in-Sports-Management
    Online-MBA-in-General-Management

    ReplyDelete
  6. 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.
    best health insurance plans in india
    best health insurance in india

    ReplyDelete
  7. 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.

    ReplyDelete