Spring boot crud operation example program

In this article, we will use the JPA (Java Persistence API) with Spring Boot for insert, update, delete and read operations.

We are using in-memory H2 database, but the same can be changed for any other relational database.

 

pom.xml


We need to add the spring-boot-starter-data-jpa and the h2 dependencies for connecting h2database using JPA.

 
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
 
 

Entity


The following Employee entity class uses JPA annotations @Entity from javax.persistence package. This @Entity annotation marks the class as Entity to be mapped to a database table.

the Long id property is marked with annotations @Id and @GeneratedValue. Therefore, id will be the primary key of the table and will be autogenerated.
 
 
package com.topjavatutorial.entity;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
 
@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;
    String name;
    int age;
 
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public Employee() {
 
    }
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String toString() {
        StringBuffer sb = new StringBuffer("Employee(");
        sb.append("Id : ");
        sb.append(id);
        sb.append(", Name : ");
        sb.append(name);
        sb.append(", Age : ");
        sb.append(age);
        sb.append(")");
        return sb.toString();
    }
 
}
 
 

Service


We will be using the following EmployeeService class(annotated with @Service) to interact with the Employee table.

It has operations for adding, updating, deleting and reading employee records.


This class has an autowired EmployeeRepository instance through which we will performing database interactions.
 
 
package com.topjavatutorial.service;
 
import java.util.List;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.topjavatutorial.entity.Employee;
import com.topjavatutorial.repo.EmployeeRepository;
 
@Service
public class EmployeeService {
    private static final Logger log = LoggerFactory
            .getLogger(EmployeeService.class);
 
    @Autowired
    EmployeeRepository empRepo;
 
    public List<Employee> getAllEmployees() {
        log.info("inside EmployeeService.getAllEmployees");
        return empRepo.findAll();
    }
 
    public Employee getEmployeeById(int id) {
        log.info("Getting employee details for ID " + id);
        return empRepo.findOne(new Long(id));
    }
 
    public void addEmployee(Employee employee) {
        log.info("Adding Employee " + employee);
        empRepo.save(employee);
    }
 
    public void updateEmployee(Employee employee) {
        log.info("Updating Employee " + employee);
        empRepo.saveAndFlush(employee);
    }
 
    public void deleteEmployee(int id) {
        log.info("Deleting employee for ID " + id);
        empRepo.delete(new Long(id));
    }
 
}
 
 

Repository


Here is the code for EmployeeRepository interface that we @Autowired in the service class.

This interface extends a JpaRepository interface that uses generics and need an entity class marked with @Entity with a property marked with @Id annotation. For our example, the entity class is Employee and id is of type Long.


JpaRepository in turn expends PagingAndSortingRepository interface that provides the methods save(), findAll(), delete() that we used with the EmployeeRepository instance in the service class.
 
 
package com.topjavatutorial.repo;
 
import org.springframework.data.jpa.repository.JpaRepository;
 
import com.topjavatutorial.entity.Employee;
 
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
 
}
 
 

Spring Boot Application class


The main class is annotated with @SpringBootApplication. This will be autogenerated with the Spring Boot app.

We have modified it to implement CommandLineRunner interface and override the run() method and added the code to call the EmployeeService methods to perform the CRUD operations.


 
package com.topjavatutorial;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
import com.topjavatutorial.entity.Employee;
import com.topjavatutorial.service.EmployeeService;
 
@SpringBootApplication
public class Application implements CommandLineRunner{
 
    private static final Logger log = LoggerFactory
            .getLogger(Application.class);
    
    @Autowired
    EmployeeService service;
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
 
    @Override
    public void run(String... arg0) throws Exception {
        service.addEmployee(new Employee("John", 23));
        service.addEmployee(new Employee("Jane", 24));
        
        
        service.getAllEmployees().forEach(
                emp -> log.info(emp.toString()));
        
        Employee temp = service.getEmployeeById(2);
        temp.setName("Janet");
        service.updateEmployee(temp);
        
        log.info("Getting All Employee Data after Update");
        service.getAllEmployees().forEach(
                emp -> log.info(emp.toString()));
        
        service.deleteEmployee(1);
        
        log.info("Getting All Employee Data after Delete");
        service.getAllEmployees().forEach(
                emp -> log.info(emp.toString()));
    }
}
 
 
Output :


Tomcat started on port(s): 8080 (http)
 

Adding Employee Employee(Id : null, Name : John, Age : 23)
Adding Employee Employee(Id : null, Name : Jane, Age : 24)


inside EmployeeService.getAllEmployees
Employee(Id : 1, Name : John, Age : 23)
Employee(Id : 2, Name : Jane, Age : 24)

Getting employee details for ID 2
Updating Employee Employee(Id : 2, Name : Janet, Age : 24)
Getting All Employee Data after Update
inside EmployeeService.getAllEmployees
Employee(Id : 1, Name : John, Age : 23)
Employee(Id : 2, Name : Janet, Age : 24)

Deleting employee for ID 1
Getting All Employee Data after Delete
inside EmployeeService.getAllEmployees
Employee(Id : 2, Name : Janet, Age : 24)

 

Source:

Spring boot tutorials with examples