Simple Spring Rest Api Example in Java

Build a REST API with Java Spring Boot

Overview

In this tutorial we are going to learn how to build a Spring Boot REST API CRUD application with PostgreSQL database as backend and Visual Studio Code as code editor.

Technologies Used

  • Java 1.8
  • Spring Boot 2.2.6
  • PostgreSQL Database
  • Visual Studio Code
  • Postman (to test the API)

Project Structure

  • EmployeeController contains mapping methods to handle RESTful requests.
  • IEmployeeDAO deals with database operations.
  • EmployeeDAO is the implementation of IEmployeeDAO.
  • Employee is the Data Model class.
  • application.properties is the configuration file where we can add application configurations such as database configuration.
  • pom.xml contains dependencies of the project.

Database Setup

We are using PostgreSQL Database as backend for this project, first we need to install PostgreSQL and setup Database.

Download the latest version of PostgreSQL from here. After the installation run pgAdmin IDE to create and setup the database.

Create a database with name employee

Under Tools -> Query Tool, run the below script to create the table emp_master.

CREATE TABLE public.emp_master (    emp_id serial NOT NULL,    emp_name character varying(200) NOT NULL,    designation character varying(200),    address character varying(500),    phone_no character varying(20),    CONSTRAINT emp_master_pkey PRIMARY KEY (emp_id) )                  

Create Spring Boot Project

In this project, we are using Visual Code to create the project. Visual Code is an Open Source and lightweight development environment developed by Microsoft. We can download it from here.

Refer Spring Boot in Visual Studio Code to create and run the project under Visual Studio Code.

POM Dependencies

We need to add the following project dependencies to pom.xml file.

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency>    <groupId>org.postgresql</groupId>    <artifactId>postgresql</artifactId>    <scope>runtime</scope> </dependency> <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>                  

Application Properties

Add database configurations to \src\main\resources\application.properties file.

spring.datasource.url=jdbc:postgresql://localhost:5432/employee spring.datasource.username=postgres spring.datasource.password=postgre@123                  

Data Model

Create a model class for Employee,

package com.coderearth.springbootcrud.model;  public class Employee {      private Integer empId;     private String empName;     private String designation;     private String address;     private String phoneNo;      /**      * @return the empId      */     public Integer getEmpId() {         return empId;     }      /**      * @param empId the empId to set      */     public void setEmpId(Integer empId) {         this.empId = empId;     }      /**      * @return the empName      */     public String getEmpName() {         return empName;     }      /**      * @param empName the empName to set      */     public void setEmpName(String empName) {         this.empName = empName;     }      /**      * @return the designation      */     public String getDesignation() {         return designation;     }      /**      * @param designation the designation to set      */     public void setDesignation(String designation) {         this.designation = designation;     }      /**      * @return the address      */     public String getAddress() {         return address;     }      /**      * @param address the address to set      */     public void setAddress(String address) {         this.address = address;     }      /**      * @return the phoneNo      */     public String getPhoneNo() {         return phoneNo;     }      /**      * @param phoneNo the phoneNo to set      */     public void setPhoneNo(String phoneNo) {         this.phoneNo = phoneNo;     } }                  

Data Access Objects

Create an Interface IEmployeeDAO with basic database CRUD functions,

package com.coderearth.springbootcrud.dao;  import java.util.List;  import com.coderearth.springbootcrud.model.Employee;  public interface IEmployeeDAO {     public List<Employee> getList();     public Employee getById(Integer empId);     public String save(Employee employee);     public String update(Employee employee);     public String delete(Integer empId); }                  

Create implementation class EmployeeDAO for IEmployeeDAO,

package com.coderearth.springbootcrud.dao;  import java.util.List;  import com.coderearth.springbootcrud.model.Employee;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository;  @Repository public class EmployeeDAO implements IEmployeeDAO {     @Autowired     JdbcTemplate jdbcTemplate;          @Override     public List<Employee> getList() {          return jdbcTemplate.query(             "SELECT "             +"emp_id,emp_name,designation,address,phone_no "             +"FROM emp_master ",             new BeanPropertyRowMapper<>(Employee.class));     }      @Override     public Employee getById(Integer empId) {         return jdbcTemplate.queryForObject(             "SELECT "             +"emp_id,emp_name,designation,address,phone_no "             +"FROM emp_master "             +"WHERE emp_id = ?",             new Object[] {empId},new BeanPropertyRowMapper<>(Employee.class));     }      @Override     public String save(Employee employee) {        jdbcTemplate.update(             "INSERT INTO emp_master "             +"(emp_name,designation,address,phone_no) "             +"VALUES (?,?,?,?)",              new Object[] {employee.getEmpName(),employee.getDesignation(),                 employee.getAddress(),employee.getPhoneNo()});          return "Saved";              }      @Override     public String update(Employee employee) {         jdbcTemplate.update(             "UPDATE emp_master "             +"SET emp_name = ?,designation = ?,address = ?,phone_no = ? "             +"WHERE emp_id = ?",             new Object[] {employee.getEmpName(),                 employee.getDesignation(),employee.getAddress(),                 employee.getPhoneNo(),employee.getEmpId()});         return "Updated";              }      @Override     public String delete(Integer empId) {         jdbcTemplate.update(             "DELETE FROM emp_master WHERE emp_id = ?",             new Object[] {empId});            return "Deleted";        }  }                  

Controllers

Finally we need to create controllers to handle RESTful API requests,

package com.coderearth.springbootcrud.controller;  import java.util.List;  import javax.validation.Valid;  import com.coderearth.springbootcrud.dao.IEmployeeDAO; import com.coderearth.springbootcrud.model.Employee;  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;  @RestController @RequestMapping(value = "/employee") public class EmployeeController {     @Autowired     IEmployeeDAO employeeDAO;      @GetMapping(value = "/list")     public List<Employee> getList() {           return employeeDAO.getList();     }      @GetMapping(value = "/get/{id}")     public Employee getById(@PathVariable(value = "id") int empId) {           return employeeDAO.getById(empId);     }          @PostMapping(value = "/save")     public String save(@Valid @RequestBody Employee employee) {           return employeeDAO.save(employee);     }      @PutMapping(value = "/update")     public String update(@Valid @RequestBody Employee employee) {           return employeeDAO.update(employee);     }      @DeleteMapping(value = "/delete/{id}")     public String delete(@PathVariable(value = "id") int empId) {           return employeeDAO.delete(empId);     } }                  

Test with Postman

Conclusion

In this tutorial, we have learned how to create a Spring Boot REST API application using Visual Studio Code and PostgreSQL.

The full source code of the sample used for this tutorial can be find on Github

dietrichhimps1952.blogspot.com

Source: https://www.coderearth.net/rest-api-java-spring-boot/

0 Response to "Simple Spring Rest Api Example in Java"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel