React (React hooks), Spring Boot and Postgresql CRUD Tutorial





Hey guys in this post, we will create full stack CRUD application with React (react hooks) and Spring boot that connects to PostgreSQL database.

Read More:

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?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.5.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springbootrestapi</artifactId>
	<version>1.0.0</version>
	<name>springbootrestapi</name>
	<description>Spring boot rest api</description>
	<properties>
		<java.version>16</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>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</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>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>
  • spring-boot-starter-web dependency for building web applications using Spring MVC.
  • It uses the tomcat as the default embedded container.
  • spring-boot-devtools dependency for automatic reloads or live reload of applications.
  • spring-boot-starter-data-jpa dependency for performing database operations.




  • lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString().
  • postgresql dependency is to store the data into the database.

Create Database


Execute the following statements in PostgreSQL –

CREATE DATABASE employeeportal;

Configure Datasource


Open application.properties file and add the following content.

spring.datasource.url=jdbc:postgresql://localhost:5432/employeeportal
spring.datasource.username=root
spring.datasource.password=scbushan05

spring.jpa.hibernate.ddl-auto=update

Note: change spring.datasource.username and spring.datasource.password as per your Postgresql database installation.

Create an Entity class


Create Employee.java class inside in.bushansirgur.springbootrestapi.entity package and add the following content

package in.bushansirgur.springbootrestapi.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Table(name = "tbl_employees")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	private String name;
	
	private String location;
	
	private String department;
}
  • All your domain models must be annotated with @Entity annotation. It is used to mark the class as a persistent Java class.
  • @Table annotation is used to provide the details of the table that this entity will be mapped to.
  • @Id annotation is used to define the primary key.
  • @GeneratedValue annotation is used to define the primary key generation strategy.
  • @Column annotation is used to define the properties of the column that will be mapped to the annotated field.

Create a Repository


Create EmployeeRepository.java interface inside in.bushansirgur.springbootrestapi.repository package and add the following content

package in.bushansirgur.springbootrestapi.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import in.bushansirgur.springbootrestapi.entity.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{

}

Create a Controller


Create EmployeeController.java class inside in.bushansirgur.springbootrestapi.controller package and add the following content

We will create 5 REST end points that performs the basic database operations such as Create, Read, Update and Delete.

package in.bushansirgur.springbootrestapi.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import in.bushansirgur.springbootrestapi.entity.Employee;
import in.bushansirgur.springbootrestapi.repository.EmployeeRepository;

@RestController
@RequestMapping("/api/v1")
@CrossOrigin("*")
public class EmployeeController {
	
	@Autowired
	private EmployeeRepository eRepo;
	
	@GetMapping("/employees")
	public List<Employee> getAllEmployees() {
		return eRepo.findAll();
	}
	
	@GetMapping("/employees/{id}")
	public Employee getEmployeeById(@PathVariable Long id) {
		return eRepo.findById(id).get();
	}
	
	@PostMapping("/employees")
	public Employee saveEmployeeDetails(@RequestBody Employee employee) {
		return eRepo.save(employee);
	}
	
	@PutMapping("/employees")
	public Employee updateEmployee(@RequestBody Employee employee) {
		return eRepo.save(employee);
	}
	
	@DeleteMapping("/employees/{id}")
	public ResponseEntity<HttpStatus> deleteEmployeeById(@PathVariable Long id) {
		eRepo.deleteById(id);
		return new ResponseEntity<>(HttpStatus.NO_CONTENT);
	}
}




Run the App


Run the application using the below maven command –

mvn spring-boot:run

Open the postman REST client and test the APIs

  • localhost:8080/api/v1/employees

Screenshot-2021-09-08-at-12-07-51-PM

  • localhost:8080/api/v1/employees

Screenshot-2021-09-08-at-12-08-35-PM

  • localhost:8080/api/v1/employees

Screenshot-2021-09-08-at-4-22-47-PM

  • localhost:8080/api/v1/8

Screenshot-2021-09-08-at-7-40-34-PM

Create React Project


In order create react project, first we should install Node.js. Download the Node.js from the below link and install on your system

https://nodejs.org/en/download/

Once Node.js is installed on your system, you can verify it by executing the below command

node -v

Using npx

To create new react project, we can use create-react-app library. Open the command prompt, enter the following command

npx create-react-app my-app

Using npm

To create using node package manager, open the command prompt enter the following command

npm init react-app my-app

Using yarn

yarn is another package manager just like npm, to create react project using yarn, open the command prompt and enter the following command

yarn create react-app my-app

This will create react starter project. Next open this project in any text editor

Install axios library


On the root of the project, enter the following command to install axios library

npm install axios
  • Axios is a simple promise based HTTP client for the browser and node.js.
  • Axios provides a simple to use library in a small package with a very extensible interface.

Install React Router DOM library


On the root of the project, enter the following command to install react-router-dom library. We will use this library for routing.

npm install react-router-dom

Intall Bootstrap library


On the root of the project, enter the following command to install bootstrap library. We will use this library to style our react application using Bootstrap 4.

npm install bootstrap@4

Configure axios library


Inside src folder, create http-common.js file and add the following content –




import axios from "axios";

export default axios.create({
    baseURL: 'http://localhost:8080/api/v1',
    headers: {
        'Content-Type': 'application/json'
    }
});

Create Employee Service


Inside src/services folder, create employee.service.js file and add the following content –

import httpClient from "../http-common";

const getAll = () => {
    return httpClient.get('/employees');
}

const create = data => {
    return httpClient.post("/employees", data);
}

const get = id => {
    return httpClient.get(`/employees/${id}`);
}

const update = data => {
    return httpClient.put('/employees', data);
}

const remove = id => {
    return httpClient.delete(`/employees/${id}`);
}
export default { getAll, create, get, update, remove };

We will import httpClient from http-common.js and we will make the HTTP requests to Spring boot backend application.

Create EmployeeList Component


Create EmployeesList.js inside src/components folder and add the following content

import { useEffect, useState } from 'react';
import { Link, useHistory } from 'react-router-dom';
import employeeService from '../services/employee.service';

const EmployeeList = () => {

  const [employees, setEmployees] = useState([]);

  const init = () => {
    employeeService.getAll()
      .then(response => {
        console.log('Printing employees data', response.data);
        setEmployees(response.data);
      })
      .catch(error => {
        console.log('Something went wrong', error);
      }) 
  }

  useEffect(() => {
    init();
  }, []);

  const handleDelete = (id) => {
    console.log('Printing id', id);
    employeeService.remove(id)
      .then(response => {
        console.log('employee deleted successfully', response.data);
        init();
      })
      .catch(error => {
        console.log('Something went wrong', error);
      })
  }

  return (
    <div className="container">
      <h3>List of Employees</h3>
      <hr/>
      <div>
        <Link to="/add" className="btn btn-primary mb-2">Add Employee</Link>
        <table className="table table-bordered table-striped">
          <thead className="thead-dark">
            <tr>
              <th>Name</th>
              <th>Location</th>
              <th>Department</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          {
            employees.map(employee => (
              <tr key={employee.id}>
                <td>{employee.name}</td>
                <td>{employee.location}</td>
                <td>{employee.department}</td>
                <td>
                  <Link className="btn btn-info" to={`/employees/edit/${employee.id}`}>Update</Link>
                  
                  <button className="btn btn-danger ml-2" onClick={() => {
                    handleDelete(employee.id);
                  }}>Delete</button>
                </td>
              </tr>
            ))
          }
          </tbody>
        </table>
        
      </div>
    </div>
  );
}

export default EmployeeList;

We have created init() method, which is responsible for fetching the list of records from API. We will call this method inside the useEffect() hook so this will call as soon as the component loads.

We also created handleDelete() method, to delete the employee based on their id. Inside this method, we will call spring boot REST api to delete an employee.

Create Add Employee Component


Create AddEmployee.js inside src/components folder and add the following content

import { useState } from "react";
import { Link, useHistory, useParams } from "react-router-dom";
import { useEffect } from "react/cjs/react.development";
import employeeService from "../services/employee.service";

const AddEmployee = () => {
    const[name, setName] = useState('');
    const[location, setLocation] = useState('');
    const[department, setDepartment] = useState('');
    const history = useHistory();
    const {id} = useParams();

    const saveEmployee = (e) => {
        e.preventDefault();
        
        const employee = {name, location, department, id};
        if (id) {
            //update
            employeeService.update(employee)
                .then(response => {
                    console.log('Employee data updated successfully', response.data);
                    history.push('/');
                })
                .catch(error => {
                    console.log('Something went wrong', error);
                }) 
        } else {
            //create
            employeeService.create(employee)
            .then(response => {
                console.log("employee added successfully", response.data);
                history.push("/");
            })
            .catch(error => {
                console.log('something went wroing', error);
            })
        }
    }

    useEffect(() => {
        if (id) {
            employeeService.get(id)
                .then(employee => {
                    setName(employee.data.name);
                    setLocation(employee.data.location);
                    setDepartment(employee.data.department);
                })
                .catch(error => {
                    console.log('Something went wrong', error);
                })
        }
    }, [])
    return(
        <div className="container">
            <h3>Add Employee</h3>
            <hr/>
            <form>
                <div className="form-group">
                    <input 
                        type="text" 
                        className="form-control col-4"
                        id="name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        placeholder="Enter name"
                    />

                </div>
                <div className="form-group">
                    <input 
                        type="text" 
                        className="form-control col-4"
                        id="department"
                        value={department}
                        onChange={(e) => setDepartment(e.target.value)}
                        placeholder="Enter Department"
                    />

                </div>
                <div className="form-group">
                    <input 
                        type="text" 
                        className="form-control col-4"
                        id="location"
                        value={location}
                        onChange={(e) => setLocation(e.target.value)}
                        placeholder="Enter Location"
                    />
                </div>
                <div >
                    <button onClick={(e) => saveEmployee(e)} className="btn btn-primary">Save</button>
                </div>
            </form>
            <hr/>
            <Link to="/">Back to List</Link>
        </div>
    )
}

export default AddEmployee;

Inside the saveEmployee() method, we are checking for the id existance, if id is present then we are calling HTTP PUT request for updating the employee. If id is not present then we are calling HTTP POST request for creating new employee.

Create NotFound Component


Create NotFound.js inside src/components folder and add the following content

const NotFound = () => {
    return (
        <div>
            <p>The page you are looking is not yet developed.</p>
        </div>
    );
}
 
export default NotFound;

Configure React Router


Open App.js and add the following content

import { BrowserRouter, Switch, Route } from 'react-router-dom';
import EmployeeList from './components/EmployeesList';
import NotFound from './components/NotFound';
import 'bootstrap/dist/css/bootstrap.min.css';
import AddEmployee from './components/AddEmployee';

function App() {
  return (
    <BrowserRouter>
      <div>
        <div>
          <Switch>
            <Route exact path="/" component={EmployeeList} />
            <Route path="/add" component={AddEmployee} />
            <Route path="/employees/edit/:id" component={AddEmployee} />
            <Route path="*" component={NotFound} />
          </Switch>
        </div>
      </div>
    </BrowserRouter>
  );
}


export default App;

At the top, we are importing the bootstrap.min.css library to style the react components.

Run the React App


On the root of the project, open the command prompt, execute the following command

Using npm

npm start

Using yarn

yarn start

This will run the application on the port, localhost:3000

Screenshot-2021-09-08-at-7-10-40-PM

Download the complete source code @ https://github.com/scbushan05/full-stack-react-and-spring-boot

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

This Post Has 4 Comments

  1. Priyan K.

    Hi Bushan,
    this line give me an error
    export default { getAll, create, get, update, remove };

    Also, this import little bit confused for me
    import httpClient from “../http-common”;

    Are there any link to source-code.?

    Thanks

      1. Priyan K.

        So many thanks Bushan, not its works perfectly

  2. Priyan K.

    So many thanks Bushan, now its works perfectly

Leave a Reply