DEV Community

priyankanandula
priyankanandula

Posted on

Create REST CRUD API With SpringBoot & SpringData-JPA.

Signed in as @priyankanandula

Hurrah 😃 , finally I started writing technical blogs to share my practical implementation knowledge in programming.
This is the My First Blog come let's start 😍.

Hope you guys will definitely gain some knowledge after completion of reading this blog.

No delay let's start this 👇

image

In this blog, you will learn how to develop RESTful web services APIs for CRUD operations on a MySQL database. The CRUD operations include Create, Retrieve, Update and Delete.

Technologies & Tools Required.

  • Java Development Kit (JDK 1.8 or newer)
  • MySQL Database server (including MySQL Workbench and MySQL Command Line Client to manage database)
  • STS(Spring Tool Suite)--4.10.0.RELEASE for creating SpringBoot projects  
  • Postman (to test RESTful APIs)

--

NOTE: You can use your favorite IDE like Eclipse, IntelliJ...

Implementation Steps :

  1. Creating SpringBoot Maven Project in STS.

  2. Creating Database in Mysql in CommandLine

  3. Creating a Table in Database using MySQL WorkBench UI.

  4. Creating an Entity Class in Project

  5. Creating a JPA Repository to perform CRUD Operations for Entity Class

  6. Configure Data Source Properties

  7. Creating a RestController Class for GET , POST, PUT ,UPDATE & DELETE HTTP Methods

  8. Run our SpringBoot Application in Embedded Tomcat Server

  9. Test our Restful services using Postman

We will create Final Project Structure as below
image


1. Creating SpringBoot Maven Project in STS :

After open STS you can go through File ->New -> Spring Starter Project

image

Provide the details as below:

1.Name - any name as your wish (in this blog I gave as ProductRestAPI)

2.Type - Maven

3.Group, Artifact & Package - you can give any values as your wish.

Here I have used...
  Group - com.priya.springweb
  Artifact - ProductRestAPI
  Package - com.priya.springweb

image

Click Next and then select the following dependencies that are required and then click finish.

1.The artifact spring-boot-starter-web is for Spring Web MVC, RESTful web services, and embedded Tomcat server.

2.The artifact spring-boot-starter-data-JPA is for Spring Data JPA and Hibernate.

  1. The artifact MySQL-connector-java is for the JDBC driver for MySQL.

image

After click finish, the project gets created as below.

image

Maven POM File:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.priya.springweb</groupId>
    <artifactId>ProductRestAPI</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>ProductRestAPI</name>
    <description>Demo project for Spring BootRestAPI</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
Enter fullscreen mode Exit fullscreen mode

2.Creating Database in Mysql in CommandLine

Open MySQL Commandlind Client and log in with the password you have given at the time of installation.

I have used root user.

Create a database with any name in this I have used myproducts.

image

image

image


3.Creating a Table in Database using MySQL WorkBench

Execute the following SQL script in WorkBench.

use myproducts;

create table product(
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
name varchar(20),
description varchar(100),
price int
);
Enter fullscreen mode Exit fullscreen mode

image


4.Creating an Entity Class in Project

Create a package like com.priya.springweb.entities and then create the Product class to map with the product table in the database as follows:

package com.priya.springweb.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;
    private String description;
    private int price;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }

}
Enter fullscreen mode Exit fullscreen mode

We have used @GeneratedValue(strategy=GenerationType.IDENTITY) because in the Database table we mentioned the id column as Auto_Increment to get these auto-generated values from a database.

NOTE: This is a simple domain model class, with class name and field names are identical to table name and column names in the databaseso we can use the minimum number of JPA annotations.


5.Creating a JPA Repository to perform CRUD Operations for Entity Class

To take advantages of Spring Data JPA, create the ProductRepository interface as below:

package com.priya.springweb.repos;

import org.springframework.data.jpa.repository.JpaRepository;

import com.priya.springweb.entities.Product;

public interface ProductRepository extends JpaRepository<Product, Integer> {

}
Enter fullscreen mode Exit fullscreen mode

NOTE : Here JpaRepository arguments represents


6.Configure Data Source Properties

In main/resources/application. properties file we need to specify database-connection information as follows.

spring.datasource.url=jdbc:mysql://localhost:3306/myproducts
spring.datasource.username=root
spring.datasource.password=root

server.servlet.context-path=/productapi
Enter fullscreen mode Exit fullscreen mode

Remember to update url, username and password according to your MySQL database server.

NOTE:Here the context path is the name of the URL at which we access the application. The default context path is empty.you can provide any name here.


7.7.Creating a RestController Class for GET , POST, PUT ,UPDATE & DELETE HTTP Methods

Here, we come to the part that actually exposes RESTful APIs for CRUD operations – a Spring controller following REST style. Create the ProductController class with some initial code as below:

package com.priya.springweb.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.priya.springweb.entities.Product;
import com.priya.springweb.repos.ProductRepository;

@RestController
public class ProductController {

    @Autowired
    private ProductRepository repository;

    @RequestMapping(value="/products",method=RequestMethod.GET)
    public List<Product> getProducts(){

        return repository.findAll();
    }

    @RequestMapping(value="/products/{id}",method=RequestMethod.GET)
    public Product getProductById(@PathVariable("id") int id) {

        return repository.findById(id).get();

    }

    @RequestMapping(value="/products/",method=RequestMethod.POST)
    public Product createProduct(@RequestBody Product product) {

        return repository.save(product);
    }


    @RequestMapping(value="/products/",method=RequestMethod.PUT)
    public Product updateProduct(@RequestBody Product product) {

        return repository.save(product);

    }

    @RequestMapping(value="/products/{id}",method=RequestMethod.DELETE)
    public void  deleteProduct(@PathVariable("id") int id) {

    repository.deleteById(id);

    }
}
Enter fullscreen mode Exit fullscreen mode
 **@RestController** - The _@RestController_ annotation is used to define the RESTful web services. It serves JSON, XML and custom response
Enter fullscreen mode Exit fullscreen mode

@RequestMapping - The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET.

@PathVariable - The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {}

@RequestBody - The @RequestBody annotation is used to define the request body content type.

NOTE:You must use @ResponseBody for Update and Create operations.


8. Run the SpringBoot Application in Embedded Tomcat Server

Right Click on your project and then select run as Spring boot app.

image


9. Testing our Restful services in Postman

1. Create Product Details - POST METHOD

URL : http://localhost:8080/productapi/products/

image

NOTE : Here in body JSON no need to pass id as it as already automatically generated by Database.

Must Select data type as JSON .

image

Yo 🤘! Data inserted successfully. Great Job.

2.Get Product Details - GET METHOD

URL - http://localhost:8080/productapi/products

Response :
[
    {
        "id": 1,
        "name": "IPhone",
        "description": "Its Awesome Product",
        "price": 1000
    },
    {
        "id": 2,
        "name": "Mac Book Pro",
        "description": "Its Amazing Product",
        "price": 3000
    },
    {
        "id": 6,
        "name": "Ipad Airpods",
        "description": "It is Good  Product",
        "price": 10000
    },
    {
        "id": 7,
        "name": "Ipad Mini",
        "description": "It is Good  Product",
        "price": 7000
    }
]
Enter fullscreen mode Exit fullscreen mode

NOTE : No need to pass any body for GET.

image

3. Get Product Details by ID - GET METHOD

URL - http://localhost:8080/productapi/products/7

Give any id of product that exists in Database Product table.

image

4.Update Product Details - PUT METHOD

URL - http://localhost:8080/productapi/products/

{
    "id": 7,
    "name": "Ipad Mini",
    "description": "It is Good  Product",
    "price": 10000
}
Enter fullscreen mode Exit fullscreen mode

Here I am updating the price to 10000 earlier we have given 7000.

NOTE : You must mention all the fields for PUT Method based upon the Id it wil lupdate the details in database table

image

5. 5.Delete Product Details by Id - DELETE METHOD

URL - http://localhost:8080/productapi/products/7

image

image

It deleted the Product successfully .


Thats it guys,WOW 😀 Good Job .We have completed creating REST API CRUD in Spring Boot.

image

Refer GIT Repository Details :

[Link] https://github.com/priyankanandula/SpringBoot-REST-API-CRUD

In next blog I will explain how to Consume these REST APIS using RestTemplate inside the code.

Have a Good Day, this is priyanka nandula signing off...

Top comments (0)