Hey guys welcome to the Full stack project with React and Spring boot, this is the Part-1 of this series. In this post, we will discuss displaying the records in HTML table.
Read More:
- Check the Complete Spring Boot Tutorials [100+ Examples]
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
- Check the Spring Boot JdbcTemplate Tutorials
Table of Contents
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>mysql</groupId>
<artifactId>mysql-connector-java</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(). mysql-connector-java
dependency is to store the data into the database.
Create Database
Open MySQL workbench and execute the following statements-
CREATE DATABASE employeeportal;
USE employeeportal;
CREATE TABLE tbl_employees
(
id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
location VARCHAR(255) NOT NULL,
department VARCHAR(255) NOT NULL
);
INSERT INTO tbl_employees(name, location, department)
VALUES("Bushan", "India", "IT");
INSERT INTO tbl_employees(name, location, department)
VALUES("Bharath", "Australia", "Marketing");
configure Datasource
Open application.properties
file and add the following content
spring.datasource.url=jdbc:mysql://localhost:3306/employeeportal
spring.datasource.username=root
spring.datasource.password=scbushan05
spring.jpa.hibernate.ddl-auto=update
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
package in.bushansirgur.springbootrestapi.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
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();
}
}
We are calling repository method findAll()
to retrieve the list of employees from database.
Run the app
Run the application using the below maven command –
mvn spring-boot:run
Open the Browser and enter the following URL – http://localhost:8080/api/v1/employees
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
Once Node.js is installed on your system, you can verify it by executing the below command
node -v
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
This will create react starter project. Next open the 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.
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');
}
export default { getAll };
Consume the REST end point
Open App.js
file. delete the existing code and add the following content –
import { useEffect, useState } from 'react';
import './App.css';
import employeeService from './services/employee.service';
const App = () => {
const [employees, setEmployees] = useState([]);
useEffect(() => {
employeeService.getAll()
.then(response => {
console.log('Printing employees data', response.data);
setEmployees(response.data);
})
.catch(error => {
console.log('Something went wrong', error);
})
}, []);
return (
<div>
<h3>List of Employees</h3>
<div>
<table border="1" cellPadding="10">
<tr>
<th>Name</th>
<th>Location</th>
<th>Department</th>
</tr>
{
employees.map(employee => (
<tr key={employee.id}>
<td>{employee.name}</td>
<td>{employee.location}</td>
<td>{employee.department}</td>
</tr>
))
}
</table>
</div>
</div>
);
}
export default App;
useState
is one of build-in react hooks available in0.16.7
version.useState
should be used only inside functional components.useState
is the way if we need an internal state and don’t need to implement more complex logic such as lifecycle methods.
Run the React app
On the root of the project, open the command prompt, execute the following command
npm start
This will run the application on the port, localhost:3000
What’s Next?
In the next part of this series, we will learn how to add React router to the react application.
Read Next: Full stack project with React and Spring boot [Part 2]
—
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.