CRUD operations with Spring Boot and JPA

Posted By : Amit Maurya | 22-Jan-2021

Spring Boot

 

Spring Boot is a Java framework used to create a micro Service. It is developed by Pivotal Team. Spring Boot provides a good platform for Java developers to develop a spring application that we can run so easily. We can create this with minimum configurations without doing the entire Spring configuration setup. 

 

JPA

 

JPA stands for Java Persistence API. It is a collection of classes and methods to persistently store a very large amount of data into the database. Each enterprise application performs database operations like storing and retrieving very large amounts of data. Jpa makes it easier to interact with the database. It forms a bridge between object models and relational databases.

 

CRUD

 

CRUD means Create, Read, Update, and Delete. It is a term used in Restful web services to perform operations on a database. 

 

You can create a spring boot project in several ways. In this tutorial, we will use Spring Starter Project. This is the fastest way to create a Spring boot project. Just click on Spring Starter Project and then name the project. Then select some dependencies given below.

 

1. Spring Web

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

</dependency>

 

2. Spring Data JPA

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

 

3. MySQL connector

<dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <scope>runtime</scope>

</dependency>

 

We can also add Spring DevTools to make the development faster.

 

Also Read: How To Integrate A 3rd Party API In Drupal

 

Now our project is ready. Now we have to configure our database. We can do all the configurations in the application.properties file.

 

spring.datasource.url=jdbc:mysql://localhost:3306/database_name

spring.datasource.username=username

spring.datasource.password=password

 

We need to create a database in MySQL and a table. Let,s say in our example we have an employee table with columns :

 

Id 

first name

last name

email

salary

department

 

We can create this table by using below SQL Query:

 

CREATE TABLE Employee

(

Id int NOT NULL,

firstname varchar(255) NOT NULL,

lastname varchar(255) NOT NULL,

email varchar(255) NOT NULL,

salary varchar(255) NOT NULL,

department varchar(255) NOT NULL,

PRIMARY KEY (Id)

);

 

Here we have created an Entity of Employee. An entity refers to a lightweight persistence domain object. It represents a table in a relational database while each entity instance represents a row in that table.

 

@Entity

public class Employee {

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Integer id;

    private String firstname;

    private String lastname;

    private String email;

    private Integer salary;

    private String department;

    //All the getters and setters
}

 

Here we have created a JPA Repository which is EmployeeRepo.java. 

 

public interface EmployeeRepo extends JpaRepository<Employee, Integer>{

}

 

Also Read: Essential Software Design Principles To Improve Code Quality

 

Now we have created a RestContrroller as EmployeeeController.java. Here we will map all requests and responses.

 

1. GET mapping to get all the employees. In this, we have used @GetMapping which will take Get requests. It will find all the records of an employee from the database with Jpa and return them in the form of ResponseEntity.

@GetMapping("/employees")

    public ResponseEntity<?> list() {

        List<Employee> employees = repo.findAll();

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

    }

 

2. GET mapping to get employee data. In this, we are taking Id with path variable. Then we find a record with id, if the record found we return it otherwise throw a NoSuchElementException which means there is no record with this Id in the database.

@GetMapping("/employee/{id}")

    public ResponseEntity<Employee> get(@PathVariable Integer id) {

        try {

            Employee employee = repo.findById(id);

            return new ResponseEntity<Employee>(employee, HttpStatus.OK);

        } catch (NoSuchElementException e) {

            return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);

        }      

    }

 

3. POST mapping to save new data. In this, we are taking data for employee records with RequestBody annotation and saving it with the help of JPA.

 

@PostMapping("/employee")

    public void add(@RequestBody Employee employee) {

        repo.save(employee);

    }

 

4. PUT Mapping to Update an existing employee. In this, we are taking an employee record and id. We find the employee record with id and save it in emp. Then we updated all the fields with employee records and then saved them with JPA.

 

@PutMapping("employee/{id}")

public void update(@RequestBody Employee employee, @PathVariable int id ) {

        Employee emp = repo.getById(id);

        emp.setFirstname(employee.getFirstname());

        emp.setLastname(employee.getLastname());

        emp.setEmail(employee.getEmail());

        emp.setSalary(employee.getSalary());

        emp.setDepartment(employee.getDepartment());

        repo.save(emp);

    }

 

5. DELETE mapping to delete an employee record. In this, we find the employee with the employee id and save it.

@DeleteMapping("/employee/{id}")
    public void delete(@PathVariable Integer id) {
        repo.deleteById(id);
    }

 

In this example, we have created a CRUD API for the Employee record. We can test our API with API clients, there are many API clients like swagger, postman, paw, Apigee, etc. 

 

Also Read: Getting Started with Spring Boot

 

Choose Oodles For SaaS App Development Services

 

We are a 360-degree software development company that provides cross-platform SaaS app development services to address varied software project requirements. We have an experienced team of Java, PHP, and Python developers who use advanced frameworks, tools, and SDKs to build scalable web and mobile applications with custom features. For more detail, reach us out at [email protected].

About Author

Author Image
Amit Maurya

Amit Maurya is a highly skilled Backend Developer with more than 2 years of experience in developing RESTAPIs and Microservices. He has expertise in using Spring Boot framework, Hibernate, Java 8, and JavaEE, and he has worked with various databases such as MySQL, PostgreSQL, Oracle, Redis, and more.He has also worked on implementing payment gateways such as Stripe, Paypal, Cryptocurrency (Metamask), Android In-App Purchases, and Apple in App Purchases. Furthermore, he has experience in implementing and maintaining Streaming servers like Ant Media and Agora. He is proficient in using version control systems like GIT and source code management tools such as GitHub and GitLab, including command line applications.He has worked on several projects, including TutorX, Fabtrack, Toosi WhatsApp Chatbot Integration, and Virtuosica.

Request for Proposal

Name is required

Comment is required

Sending message..