in this blog, creating custom rest API. Rest API that means use Rest Controller @RestController on Configuration class. for the view, we use the Postman tool . where we testing our request and response generated by URL. Here showing the development process one by one.
| HTTP Method | Url Mapping | CRUD Action |
|---|---|---|
| POST | customer/customersave | Create a new customer |
| GET | customer/all-customer-list | Read a list of customers |
| GET | customer/single-customer-view/{theCustomerId} | Read a single customer |
| PUT | customer/update | Update an exiting customer |
| DELETE | customer/delete/{theCustomerId} | Delete an existing customer |
Create Spring Boot project using STS
POM.XML
<?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.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.code4devops</groupId> <artifactId>SpringBootRestApiWithHibernate</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringBootRestApiWithHibernate</name> <description>Spring Boot RestApi With Hibernate</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>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </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> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Note: write some database information in appliction.properties
appliction.properties
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot _build_a_rest_api_with_hibernate?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root
Customer.java
package com.code4devops.entity;
import java.util.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;
import com.fasterxml.jackson.annotation.JsonFormat;
@Entity
@Table(name = "customer_detail")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "customer_id", length = 10, nullable = false)
private int customer_id;
@Column(name = "customer_fname", length = 45, nullable = true)
private String customer_fname;
@Column(name = "customer_lname", length = 45, nullable = true)
private String customer_lname;
@Column(name = "customer_mobile", length = 45, nullable = true)
private String customer_mobile;
@Column(name = "customer_email", length = 45, nullable = true)
private String customer_email;
@Column(name = "customer_join_date", length = 45, nullable = true)
@JsonFormat(pattern="yyyy-MM-dd")
private Date customer_join_date;
public Customer() {}
public Customer(String customer_fname, String customer_lname, String customer_mobile, String customer_email) {
this.customer_fname = customer_fname;
this.customer_lname = customer_lname;
this.customer_mobile = customer_mobile;
this.customer_email = customer_email;
}
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getCustomer_fname() {
return customer_fname;
}
public void setCustomer_fname(String customer_fname) {
this.customer_fname = customer_fname;
}
public String getCustomer_lname() {
return customer_lname;
}
public void setCustomer_lname(String customer_lname) {
this.customer_lname = customer_lname;
}
public String getCustomer_mobile() {
return customer_mobile;
}
public void setCustomer_mobile(String customer_mobile) {
this.customer_mobile = customer_mobile;
}
public String getCustomer_email() {
return customer_email;
}
public void setCustomer_email(String customer_email) {
this.customer_email = customer_email;
}
public Date getCustomer_join_date() {
return customer_join_date;
}
public void setCustomer_join_date(Date customer_join_date) {
this.customer_join_date = customer_join_date;
}
@Override
public String toString() {
return customer_id + "|" + customer_fname + "|"+ customer_lname + "|" + customer_mobile + "|" + customer_email+ "|" + customer_join_date;
}
}
CustomerDataAccessObject.java
package com.code4devops.dao;
import java.util.List;
import com.code4devops.entity.Customer;
public interface CustomerDataAccessObject {
public abstract List<Customer> findAll();
public abstract Customer findById(int customerId);
public abstract void save(Customer customer);
public abstract void deleteById(int customerId);
}
CustomerDataAccessObjectImplementation.java
package com.code4devops.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.code4devops.entity.Customer;
@Repository
public class CustomerDataAccessObjectImplementation implements CustomerDataAccessObject{
@Autowired
private EntityManager entityManager;
@Override
public List<Customer> findAll() {
//get the current hibernate session
Session session=entityManager.unwrap(Session.class);
//create a query
//table name same as class name here in query it case sensitive
Query theQuery=session.createQuery("from Customer", Customer.class);
//execute query and get result list
List<Customer> customerList= theQuery.getResultList();
//return the results
return customerList;
}
@Override
public Customer findById(int customerId) {
//get the current hibernate session
Session session=entityManager.unwrap(Session.class);
//get the Customer Object by customerId
Customer customer=session.get(Customer.class, customerId);
//return the results
return customer;
}
@Override
public void save(Customer customer) {
//get the current hibernate session
Session session=entityManager.unwrap(Session.class);
//Remember One Thing : if id=0 the insert else update
session.saveOrUpdate(customer);
}
@Override
public void deleteById(int customerId) {
//get the current hibernate session
Session session=entityManager.unwrap(Session.class);
//delete Object with primary key
Query theQuery = session.createQuery("delete from Customer where customer_id=:customer_id");
theQuery.setParameter("customer_id", customerId);
theQuery.executeUpdate();
}
}
CustomerService.java
package com.code4devops.service;
import java.util.List;
import com.code4devops.entity.Customer;
public interface CustomerService {
public abstract List<Customer> findAll();
public abstract Customer findById(int customerId);
public abstract void save(Customer Customer);
public abstract void deleteById(int customerId);
}
CustomerServiceImplementation.java
package com.code4devops.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.code4devops.dao.CustomerDataAccessObject;
import com.code4devops.entity.Customer;
@Service
public class CustomerServiceImplementation implements CustomerService{
@Autowired
private CustomerDataAccessObject customerDataAccessObject;
@Override
@Transactional
public List<Customer> findAll() {
return customerDataAccessObject.findAll();
}
@Override
@Transactional
public Customer findById(int customerId) {
return customerDataAccessObject.findById(customerId);
}
@Override
@Transactional
public void save(Customer customer) {
customerDataAccessObject.save(customer);
}
@Override
@Transactional
public void deleteById(int customerId) {
customerDataAccessObject.deleteById(customerId);
}
}
RestControllerForCustomer.java
package com.code4devops;
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 com.code4devops.entity.Customer;
import com.code4devops.service.CustomerService;
@RestController
@RequestMapping("customer")
public class RestControllerForCustomer {
@Autowired
private CustomerService customerService;
//expose "customer/customersave"
@PostMapping("/customersave")
public Customer getEmployeeSave(@RequestBody Customer theCustomer) {
theCustomer.setCustomer_id(0);
customerService.save(theCustomer);
return theCustomer;
}
//expose "customer/all-customer-list"
@GetMapping("/all-customer-list")
public List<Customer> getAllEmployeeList() {
return customerService.findAll();
}
//expose customer/single-customer-view/{theCustomerId}
@GetMapping("/single-customer-view/{theCustomerId}")
public Customer getSingleCustomerView(@PathVariable int theCustomerId) {
return customerService.findById(theCustomerId);
}
//expose "customer/delete/1"
@DeleteMapping("/delete/{theCustomerId}")
public String getEmployee(@PathVariable int theCustomerId) {
Customer customer=customerService.findById(theCustomerId);
if( customer == null) {
throw new RuntimeException("Employee id not found :"+ theCustomerId);
}
customerService.deleteById(theCustomerId);
return "Delete customer id :" +theCustomerId;
}
//expose "customer/update"
@PutMapping("/update")
public Customer getEmployeeUpdate(@RequestBody Customer customer) {
customerService.save(customer);
return customer;
}
}
SpringBootRestApiWithHibernateApplication.java
package com.code4devops;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootRestApiWithHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApiWithHibernateApplication.class, args);
}
}