Skip to main content

Spring Boot CRUD operation with Rest API, JPA and MySql | Programming Blog

Spring Boot REST full API CRUD operation with MySql, JPA

Spring Boot CRUD with MySql, JPA, Hibernate and Rest API    

In this Spring boot CRUD example, you will learn how to develop Spring boot application with REST full web service and Create, Read, Update and Delete data from MySql.

1. Start creating project in Spring Boot

We uses Spring Initializr for creating our application. Go to following link, add artifact and name of your project.

We uses PostMan for test our REST API. Downlaod PostMan from following link :-

In this tutorial, following MySql version used.

  • 5.0.27

Add Three dependencies :-

  1. Spring Web - Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container.
  2. Spring Data JPA - Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.
  3. MySql Driver - MySQL JDBC and R2DBC driver.

In this tutorial we used following Project Structure.

Spring boot crud example project structure

Check out following image

Spring Boot CRUD operations with MySql

After all done, click on GENERATE button it will download .zip file. extract that and import in your IDE. we uses Eclipse IDE.

2. Create MySql Schema and Table

CREATE TABLE `book` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `bookname` VARCHAR(30) NOT NULL,
  `author` VARCHAR(30),
  `price` INT NOT NULL,
   PRIMARY KEY (`id`)
);

3. Configure Maven Dependencies

We already includes all maven dependencies. Following the pom.xml file code.

<?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.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringBootCrudWithMySql</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootCrudWithMySql</name>
    <description>Demo project for Spring Boot</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>
            <version>5.1.34</version>
        </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>

4. Configure application.properties file

application.properties file located in your project under the src/main/resources folder.

We define our MySql connectivity code here. we added DataSource url, DriverClassName, username and password.

spring.datasource.url = jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = root

#The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

5. Create Model Class

In this we created POJO (Plain Old Java Object).

Book.java

package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    
    @Column
    private String bookname;
    
    @Column
    private String author;
    
    @Column
    private int price;
    
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    
    public String getBookname()    {
        return bookname;
    }
    
    public void setBookname(String bookname) {
        this.bookname = bookname;
    }
    
    public String getAuthor() {
        return author;
    }
    
    public void setAuthor(String author) {
        this.author = author;
    }
    
    public int getPrice() {
        return price;
    }
    
    public void setPrice(int price) {
        this.price = price;
    }
}

6. Create Repository Interface

In this we create Interface for repository that extends CrudRepository. 

In example, we extends JpaRepository but we can also extends CrudRepository. if you want to learn more about them and difference between CrudRepository and JpaRepository then check out this :-

BooksRepository.java

package com.example.repository;

import org.springframework.data.repository.CrudRepository;
import com.example.model.Book;

public interface BooksRepository extends JpaRepository<Book, Integer> {

}

7. Create Service class

BookService.java

package com.example.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.model.Book;
import com.example.repository.BookRepository;

@Service
public class BookService {

    @Autowired
    BookRepository bookRepository;

    public List<Book> loadAllBooks() {
        return (List<Book>) bookRepository.findAll();
    }

    public Book loadBookById(int id) {
        return bookRepository.findById(id).get();
    }
    
    public Book saveBook(Book book) {
        bookRepository.save(book);
        return loadBookById(book.getId());
    }

    public void deleteBook(int id) {
        bookRepository.deleteById(id);
    }
    
    public Book updateBook(Book book) {
        return bookRepository.save(book);
    }

}

8. Create Controller class

 BookController.java

package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.Book;
import com.example.service.BookService;

@RestController
public class BookController {

    @Autowired
    BookService bookService;

    // Get All Books
    @GetMapping("/books")
    private List<Book> getAllBooks() {
        return bookService.loadAllBooks();
    }

    // Get book based on given id
    @GetMapping("/books/{id}")
    private Book getBooks(@PathVariable("id") int id) {
        return bookService.loadBookById(id);
    }

    // Save book in DataBase
   @PostMapping("/books/save")
    private Book saveBook(@RequestBody Book book) {
        return bookService.saveBook(book);
    }

    // Update saved data in DataBase
  @PutMapping("/books/update")
    private Book update(@RequestBody Book book) {
        bookService.updateBook(book);
        return book;
    }

    // Delete book based on given id
    @DeleteMapping("/books/delete/{id}")
    private void deleteBook(@PathVariable("id") int id) {
        bookService.deleteBook(id);
    }
}

There is already one Java Class available when you create project from start.spring.io. In this Application class Main method is already there. 

Now time to run our web app.

We can run our application using following ways :-

  1. Go to Application class and Right click and Run As -> Java Application or Spring Boot App
  2. Right click on your project  Run As -> Java Application or Spring Boot App

So lets see how CRUD operation works. lets start with save

1. Save (Create)

Save Api using spring boot in postman


Enter API for save and select POST method from dropdown

http://localhost:8080/books/save

{"bookname":"Clean Code","author":"Martin Robert C","price":500}

Enter above request body for save there is no need to add id in response, because we define id as primary key. So id is set automatically. 

As you can see, after save successfully we get response with id.

2. Update

spring boot rest api for update

We change the price of "Clean Code" book from 500 to 200 using update api.

3. Get and Get all (Read)

get data using rest api in spring boot
For get one data we have to pass id in our Rest Api. like in above example. and if we does not pass any id then it returns all Books that are present in DataBase.
Spring Boot Crud operation with MySql Demo | Programming Blog


4. delete

delete operation using rest api in spring boot

As you can see we get status 200 Ok that means out data successfully deleted.

You can download this Project from following GIT repository :-

If you have any query regarding above tutorial then comment down.

Thank You.

In this article we learn how to use Rest Api through Postman. Next we will seen how to perform CRUD operation using UI (User Interface). We will use Thymeleaf template engine for display our data.

Comments

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last