What is Spring Boot in Java ? Spring Boot Crud Operations

Back to Blog
Spring boot crud operations

What is Spring Boot in Java ? Spring Boot Crud Operations

Agenda

In this blog, we are going to talk about the following points:-

  1. What is Spring Boot?
  2. Spring Boot Application Architecture
  3. Why Spring Boot?
  4. Some important Annotation of Spring boot
  5. Let’s set up a Spring Boot application
  6. Some Important Dependency for Spring Boot Project
  7. Entity
  8. Repository
  9. Service
  10. Controller
  11. Helper 
  12. Constant
  13. Router

What is Spring Boot?

Spring Boot is an open-source, microservice-based Java web framework. The Spring Boot framework creates a fully production-ready environment that is completely configurable using its prebuilt code within its codebase.

Spring Boot Application Architecture

Application Architecture

Why Should You Use Spring Boot?

  1. Fast and easy development of Spring-based applications
  2. No need for the deployment of war files
  3. The ability to create standalone applications
  4. Helping to directly embed Tomcat, Jetty, or Undertow into an application
  5. No need for XML configuration
  6. Reduced amounts of source code
  7. Additional out-of-the-box functionality
  8. Easy start
  9. Simple setup and management
  10. Large community and many training programs to facilitate the familiarization period
Some Important Annotations of Spring Boot

Annotation

Spring Boot Application and Perform CRUD Operation

Step 1: Open Spring Initializr http://start.spring.io.

Step 2: Select the Spring Boot version 2.3.0.M1.

Step 2: Provide the Group name. We have provided com.demo.

Step 3: Provide the Artifact Id. We have provided spring-boot-crud-operation.

Step 5: Add the dependencies Spring Web, Spring Data JPA

Step 6: Click on the Generate button. When we click on the Generate button, it wraps the specifications in a Jar file and downloads it to the local system.

Spring Boot application

Dependencies for Spring Boot Project

// Spring boot validation
<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

//Jwt Token Security
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

//Json Dependency 
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20220320</version>
</dependency>

spring-boot-starter-web -> Services on Tomcat - typically REST services using Spring MVC for web layer
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
 
spring-boot-starter-web-services -> SOAP services
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web-services</artifactId>
</dependency>

spring-boot-starter-jersey -> Services on Tomcat - typically REST services using Jersey implementation of JAX-RS for web layer
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

MySQL Connector Java Maven Dependency
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

//Spring boot swagger Generator
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.3</version>
</dependency>
//Dependency for setter getter and constructors
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

//Spring boot Jpa Dependency (ORM)
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Read Also – Difference Between CodeIgniter 3 and CodeIgniter 4 versions

Create The Blow Class in Your Project

Spring boot Jpa Dependency

Entity Class – Book.java

package com.example.msn.Entities;
 
import java.sql.Timestamp;
import java.time.LocalDateTime;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
import lombok.Data;
 
@Entity
@Data
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
 
    private String name;
    private String Qty;
    private Timestamp createdOn;
}

Repository Class – BookRepository.java
package com.example.msn.Repository;

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

import org.springframework.stereotype.Repository;

import com.example.msn.Entities.Book;

@Repository

public interface BookRepository extends JpaRepository<Book,Integer> {

}
Service Class – BookService.java

packagecom.example.msn.Services;

import java.util.List;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.example.msn.Entities.Book;

import com.example.msn.Repository.BookRepository;

@Service

publicclassBookService {

@Autowired

    private BookRepository bookRepository;

    public Void deleteBook(Integer id) {

        bookRepository.deleteById(id);

        return null;

    }

    public List<Book> getBooks() {

        List<Book> books = bookRepository.findAll();

        return books;

    }

    public Book addBook(Book book1) {

        Book book = bookRepository.save(book1);

        return book;

    }

    public  Optional<Book> findById(Integer id) {

        Optional<Book> book1 = bookRepository.findById(id);

        return book1;

    }

}

Controller – BookController.java

package com.example.msn.Controllers;

import java.util.List;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import com.example.msn.Constants.ResMesConstants;

import com.example.msn.Entities.Book;

import com.example.msn.Helpers.ApiResponse;

import com.example.msn.Requests.AddBookRequest;

import com.example.msn.Requests.EditBookRequest;

import com.example.msn.Services.BookService;

@Controller

public class BookController {

    @Autowired

    private BookService bookService;

    public ResponseEntity<Object> deleteBook(Integer id) {

        bookService.deleteBook(id);

        ApiResponse apiResponse = new ApiResponse(false, ResMesConstants.BOOK_DELETED_SUCCESSFULLY,

                HttpStatus.OK,

                null);

        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);

    }

    public ResponseEntity<Object> getBooks() {

        List<Book> book = bookService.getBooks();

        ApiResponse apiResponse = new ApiResponse(false, ResMesConstants.RECORD_FOUND_SUCCESSFULLY,

                HttpStatus.OK,

                book);

        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);

    }

    public ResponseEntity<Object> editBook(EditBookRequest editBookRequest) {

        Optional<Book> book1 = bookService.findById(editBookRequest.getId());

        if (book1.get() == null) {

            ApiResponse apiResponse = new ApiResponse(false, ResMesConstants.SOMETHING_WENT_WRONG,

                    HttpStatus.PRECONDITION_FAILED,

                    null);

            return new ResponseEntity<Object>(apiResponse, HttpStatus.PRECONDITION_FAILED);

        }

        book1.get().setName(editBookRequest.getBookname());

        book1.get().setQty(editBookRequest.getQty());

        Book book = bookService.addBook(book1.get());

        if (book == null) {

            ApiResponse apiResponse = new ApiResponse(false, ResMesConstants.SOMETHING_WENT_WRONG,

                    HttpStatus.PRECONDITION_FAILED,

                    null);

            return new ResponseEntity<Object>(apiResponse, HttpStatus.PRECONDITION_FAILED);

        }

        ApiResponse apiResponse = new ApiResponse(false, ResMesConstants.BOOK_UPDATED_SUCCESSFULLY, HttpStatus.OK,

                null);

        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);

    }

    public ResponseEntity<Object> addBook(AddBookRequest addBookRequest) {

        Book book1 = new Book();

        book1.setName(addBookRequest.getBookname());

        book1.setQty(addBookRequest.getQty());

        Book book = bookService.addBook(book1);

        ApiResponse apiResponse = new ApiResponse(false, ResMesConstants.BOOK_ADDED_SUCCESSFULLY, HttpStatus.OK,

                book);

        return new ResponseEntity<Object>(apiResponse, HttpStatus.OK);

    }

}

Helper – ApiResponse.java

package com.example.msn.Helpers;

import org.springframework.http.HttpStatus;

import lombok.Data;

@Data

public class ApiResponse {

    private boolean error;

    private String message;

    private HttpStatus HttpStatus;

    private Object data;

    public ApiResponse(boolean error, String message, HttpStatus httpStatus, Object data) {

        this.error = error;

        this.message = message;

        this.HttpStatus = httpStatus;

        this.data = data;

    }

}

Constants Constant.java

package com.example.msn.Constants;

public interface ResMesConstants {

    public final String RECORD_FOUND_SUCCESSFULLY = "Record found Successfully";

    public final String RECORD_NOT_FOUND = "Record not found";

    public final String INVALID_TOKEN = "Invalid token";

    public final String INVALID_REQUEST = "Invalid request";

    public final String EMAIL_IS_ALREADY_REGISTERED = null;

    public final String BOOK_DELETED_SUCCESSFULLY = null;

    public final String BOOK_UPDATED_SUCCESSFULLY = null;

    public final String BOOK_ADDED_SUCCESSFULLY = null;

    public final String SOMETHING_WENT_WRONG = "something went wrong!";

    public final String LOGIN_SUCCESSFULLY = "Login successfully";

    public final String INVALID_USER_PASSWORD = "Invalid user password";

    public final String PRECONDITION_FAILED = "Precondition Failed";

    public final String MOBILE_NO_LENGTH_MUST_9 = "Mobile no length must >9";

    public final String USER_NAME_CAN_NOT_BE_EMPTY = "User Name Can not be empty";

    public final String PASSWORD_LENGTH_MUST_5 = "Password length must >5 ";

    public final String MOBILE_NO_IS_ALREADY_REGISTERED = "Mobile no is already registered!";

    public final String REGISTRATION_SUCCESSFULLY = "Registration successfully ";

    public final String INVALID_MOBILE_NO = "Invalid Mobile No ";

}

Read Also-  Install The Telescope In Laravel

Router openApi.java
package com.example.msn.Routes;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

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.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import com.example.msn.Controllers.BookController;

import com.example.msn.Requests.AddBookRequest;

import com.example.msn.Requests.EditBookRequest;

import com.example.msn.Requests.LoginEntityRequest;

import com.example.msn.Requests.RegistrationRequest;

@RestController

public class OpenApi {

    @Autowired

    private BookController bookController;

    // addBook api

    @PostMapping(path = "/addBook", consumes = "application/json")

    public ResponseEntity<Object> addBook(@RequestBody  AddBookRequest addBookRequest) {

        return bookController.addBook(addBookRequest);

    }

    // editBook api

    @PostMapping(path = "/editBook", consumes = "application/json")

    public ResponseEntity<Object> editBook(@RequestBody EditBookRequest editBookRequest) {

        return bookController.editBook(editBookRequest);

    }

    // getBooks api

    @GetMapping(path = "/getBooks")

    public ResponseEntity<Object> getBooks() {

        return bookController.getBooks();

    }

    // deleteBook api

    @PostMapping(path = "/deleteBook/{id}")

    public ResponseEntity<Object> deleteBook(@PathVariable(name = "id" ) String id) {

        return bookController.deleteBook(Integer.valueOf(id));

    }

}

Bitbucket

Share this post

Back to Blog