Hey guys, Bushan here, Welcome back to B2 Tech. Today in this article we are going discuss how we can create REST API using Spring boot, hibernate and MySQL. We are going to create End-to-End REST API which is connected to Database and we will discuss all the CRUD operations, so let’s get started.
Table of Contents
Tools and Technologies used,
- Spring Boot 2.1.1
- Hibernate
- Spring MVC
- MySQL
- Maven
- Eclipse Oxygen IDE
Creating the Project
To create a Spring boot project, Spring provides a web tool called Spring Initializer. Just go to https://start.spring.io/ and follow the below steps
Provide the details as follows
- Group: in.bushansirgur.springbootcrud
- Artifact: springbootcrudapi
- Dependencies: Web, JPA, Devtools, MySQL
Once all the details entered, click on the Generate Project. Spring will create a starter project based on the dependencies you entered and download the project in zip format.
Unzip the project and open in Eclipse IDE or STS IDE.
Project Structure
RELATED: Create a Full Stack Application using Angular + Spring MVC + Hibernate + MySQL
pom.xml
Following are the dependencies which we added while creating the project
<?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 http://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.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>in.bushansirgur.springbootcrud</groupId> <artifactId>springbootcrudapi</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springbootcrudapi</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <start-class>in.bushansirgur.springbootcrud.springbootcrudapi.SpringbootcrudapiApplication</start-class> </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>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </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>
Configuring MySQL database
To configure MySQL database follow the below steps,
STEP 1: Go to MySQL database and create a database
CREATE DATABASE crudapi;
STEP 2: Select the database
USE crudapi;
STEP 3: Create a table
CREATE TABLE tbl_employee ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255), gender VARCHAR(255), department VARCHAR(255), dob DATE );
STEP 4: Open application.properties and add the following in it
spring.datasource.url=jdbc:mysql://localhost:3306/crudapi spring.datasource.username=root spring.datasource.password=
add the username and password as per your MySQL installation
Creating an Employee model
Employee.java
Create an Employee model class under the in.bushansirgur.springbootcrud.springbootcrudapi.model package
package in.bushansirgur.springbootcrud.springbootcrudapi.model; import java.sql.Date; 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 = "tbl_employee") public class Employee { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column private Integer id; @Column private String name; @Column private String gender; @Column private String department; @Column private Date dob; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", gender=" + gender + ", department=" + department + ", dob=" + dob + "]"; } }
Creating the DAO
Create EmployeeDAO and EmployeeDAOImpl inside the in.bushansirgur.springbootcrud.springbootcrudapi.dao package
EmployeeDAO.java
The Interface defines the following 4 methods
package in.bushansirgur.springbootcrud.springbootcrudapi.dao; import java.util.List; import in.bushansirgur.springbootcrud.springbootcrudapi.model.Employee; public interface EmployeeDAO { List<Employee> get(); Employee get(int id); void save(Employee employee); void delete(int id); }
EmployeeDAOImpl.java
This class implements the EmployeeDAO and provide the implementation for all the 4 methods.
package in.bushansirgur.springboot.crudapi.dao; import java.util.List; import javax.persistence.EntityManager; import org.hibernate.Session; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import in.bushansirgur.springboot.crudapi.model.Employee; @Repository public class EmployeeDAOImpl implements EmployeeDAO { @Autowired private EntityManager entityManager; @Override public List<Employee> get() { Session currentSession = entityManager.unwrap(Session.class); Query<Employee> query = currentSession.createQuery("from Employee", Employee.class); List<Employee> list = query.getResultList(); return list; } @Override public Employee get(int id) { Session currentSession = entityManager.unwrap(Session.class); Employee employeeObj = currentSession.get(Employee.class, id); return employeeObj; } @Override public void save(Employee employee) { Session currentSession = entityManager.unwrap(Session.class); currentSession.saveOrUpdate(employee); } @Override public void delete(int id) { Session currentSession = entityManager.unwrap(Session.class); Employee employeeObj = currentSession.get(Employee.class, id); currentSession.delete(employeeObj); } }
EmployeeService.java
Create EmployeeService and EmployeeServiceImpl inside the in.bushansirgur.springbootcrud.springbootcrudapi.service package. The Interface defines the following 4 methods
package in.bushansirgur.springboot.crudapi.service; import java.util.List; import in.bushansirgur.springboot.crudapi.model.Employee; public interface EmployeeService { List<Employee> get(); Employee get(int id); void save(Employee employee); void delete(int id); }
EmployeeServiceImpl.java
This class implements the EmployeeService and provide the implementation for 4 methods
package in.bushansirgur.springboot.crudapi.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import in.bushansirgur.springboot.crudapi.dao.EmployeeDAO; import in.bushansirgur.springboot.crudapi.model.Employee; @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDAO employeeDAO; @Transactional @Override public List<Employee> get() { return employeeDAO.get(); } @Transactional @Override public Employee get(int id) { return employeeDAO.get(id); } @Transactional @Override public void save(Employee employee) { employeeDAO.save(employee); } @Transactional @Override public void delete(int id) { employeeDAO.delete(id); } }
EmployeeController.java
Create EmployeeController inside the in.bushansirgur.springbootcrud.springbootcrudapi.controller package. This class defines the 5 following methods
package in.bushansirgur.springboot.crudapi.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.RequestMapping; import org.springframework.web.bind.annotation.RestController; import in.bushansirgur.springboot.crudapi.model.Employee; import in.bushansirgur.springboot.crudapi.service.EmployeeService; @RestController @RequestMapping("/api") public class EmployeeController { @Autowired private EmployeeService employeeService; @PostMapping("/employee") public Employee save(@RequestBody Employee employeeObj) { employeeService.save(employeeObj); return employeeObj; } @GetMapping("/employee") public List<Employee> get(){ return employeeService.get(); } @GetMapping("/employee/{id}") public Employee get(@PathVariable int id) { Employee employeeObj = employeeService.get(id); if(employeeObj == null) { throw new RuntimeException("Employee not found for the Id:"+id); } return employeeObj; } @PutMapping("/employee") public Employee update(@RequestBody Employee employeeObj) { employeeService.save(employeeObj); return employeeObj; } @DeleteMapping("/employee/{id}") public String delete(@PathVariable int id) { employeeService.delete(id); return "Employee has been deleted with id:"+id; } }
CrudapiApplication.java
This is the main class, it is the entry point to the application
package in.bushansirgur.springboot.crudapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CrudapiApplication { public static void main(String[] args) { SpringApplication.run(CrudapiApplication.class, args); } }
That’s it! Now the right click on the main class and choose Run as Java application. The application starts in default port 8080. You can test the application by using any RestClient like Postman etc..
That’s all for now. Thank you so much for tuning in, I hope this post helped you in one or the other way. If you have any questions regarding this post, reach out to me @ [email protected]