Add Record to a table in React JS, Spring Boot, and MYSQL. In this article, we will learn How to create an add/create functionality using React JS and Spring Boot Application.
Insert data into MYSQL using React JS, Spring Boot, and RestAPI
We will develop a simple application where we will post data to the server using React JS at the frontend, spring boot at the backend, and using Spring Data JPA at the Data Access Layer.
Let us divide the development process into two parts:
- Frontend: React JS
- Backend: Spring Boot
Note:
- If you want to know How to display only the list on the web page using React JS and Spring Boot application check this article https://codebun.com/how-to-create-spring-boot-and-reactjs-application/.
- If you want to know How to create pagination in React JS with Spring boot application check this article Dynamic Pagination.
Tools and Technologies Used in Spring boot and ReactJs app
- React JS
- Spring Boot
- MYSQL Database
- Spring Data JPA
Create Backend Part using Spring boot, Spring Data JPA and MYSQL
Create a Database
The first step is to create a database name ‘db_demo’ using the MYSQL command line or Workbench.
Create database db_demo
Create Project
Create a project using Spring Initializr. If you don’t know how to create a project using the same check this article https://codedec.com/tutorials/how-to-create-spring-boot-project-using-spring-initializr/
Import a Project
Now, it’s time to import the project into STS. Go to File > Import > Maven > Existing Maven Project > Next > Browse > Select the project > Finish. Now, it will take time to import the project, and similarly, all the dependencies would be added.
Configure application. properties file
# change the port server.port=8888 #Database Configrations spring.datasource.url=jdbc:mysql://localhost:3306/db_demo spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=root spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto = update
Create a Model Class
Now, we will create a Model class called Book.java. I have used the Lombok library to remove boilerplate code. In case you want to know what is Lombok check this article Lombok Tutorial.
Book.java
package com.abc.in.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.springframework.context.annotation.EnableAspectJAutoProxy; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "book") public class Book { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private String bookName; private String authorName; private long price; }
Create Repository Interface
Now, we will create a Data Access Layer called BookRepository which will extend JPARepository.
package com.abc.in.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.abc.in.model.Book; public interface BookRepository extends JpaRepository<Book, Long>{ }
Create a Controller
The client request is sent to the controller which acts as an API layer that will have the endpoints for REST API.
package com.abc.in.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; 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.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.abc.in.model.Book; import com.abc.in.repository.BookRepository; @CrossOrigin(origins = "http://localhost:3000/") @RestController public class BookController { @Autowired private BookRepository bookRepository; //Add a Book @PostMapping("/books") public ResponseEntity<Book> addBooks(@RequestBody Book book) { return new ResponseEntity<Book>(bookRepository.save(book), HttpStatus.OK); } }
- Mark the BookController with @RestController.
- Now, create addBook() method that would call the save() method of the Repository class.
Now, Go to the main class and run the application
package com.abc.in; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.abc.in.model.Book; import com.abc.in.repository.BookRepository; @SpringBootApplication public class SpringBootBackendPartApplication{ public static void main(String[] args) { SpringApplication.run(SpringBootBackendPartApplication.class, args); } }
Create Frontend Part using ReactJS
Now, we will create a frontend part of the application using React JS. Open Cmd prompt > Go to the folder where you want to create a project with the help of command prompt codes > enter the command npx create-react-app book-frontend.
- Now, open Visual Studio Code IDE and open the book-frontend app.
- Here, you will see all the required folders and files.
We will be using bootstrap in React JS. So, open the terminal of VS code and type the following command
D:\Job Stuff\My_Study\React JS\book-frontend>npm install bootstrap
You have to install React Bootstrap also by using the following command
D:\Job Stuff\My_Study\React JS\book-frontend> npm install react-bootstrap
Install Axios library that is going to make a request to the endpoints which we have created at the backend.
D:\Job Stuff\My_Study\React JS\book-frontend> npm install axios
Create AddBookComponent.js
Inside the src folder, create a components folder and add AddBookComponent.js and add the following lines of code.
import React, { useState } from 'react' import axios from 'axios'; function AddBookComponent() { //Step 1: const [book, setBook] = useState({ bookName: '', authorName: '', price: '' }); //Step 3: const onInputChange = e => { setBook({ ...book, [e.target.name]: e.target.value }) } const { bookName, authorName, price } = book; const FormHandle = e => { e.preventDefault(); addDataToServer(book) } const addDataToServer = (data) => { axios.post("http://localhost:8889/books", data).then( (response) => { console.log(response); alert("Book Added Successfully"); }, (error) => { console.log(error); alert("Operation failed"); } ); } return ( <div> <div className="container"> <div className="w-75 mx-auto shadow p-5 mt-2 bg-light"> <div class="jumbotron"> <h1 class="display-4 text-center">Add Books!</h1> <div> <form onSubmit={e => FormHandle(e)}> <div class="form-group"> <label for="exampleInputEmail1">Book Name</label> <input type="text" class="form-control" name="bookName" placeholder="Enter Here" value={bookName} onChange={(e) => onInputChange(e)} /> </div> <div class="form-group"> <label for="exampleInputPassword1">Book Author</label> <input type="text" class="form-control" name="authorName" placeholder="Enter Here" value={authorName} onChange={(e) => onInputChange(e)} /> </div> <div class="form-group"> <label for="exampleInputPassword1">Book Price</label> <input type="text" class="form-control" name="price" placeholder="Enter Here" value={price} onChange={(e) => onInputChange(e)} /> </div> <div className="container text-center"> <button type="submit" class="btn btn-outline-secondary my-2 text-center mr-2">Add Book</button> <button type="reset" class="btn btn-outline-primary text-center mr-2">Clear Book</button> </div> </form> </div> </div> </div> </div> </div> ) } export default AddBookComponent
Now, let us divide the code and understand the working of it.
- First, add the useState to have a state variable in functional components as shown below.
const [book, setBook] = useState({ bookName: '', bookAuthor: '', price: '' });
- Now, destructure the element from the array as shown below
const { bookName , authorName , price} = book;
- Now, create a form field and call the method onInputChange on onChange() method. Pass the value and name attribute. (Repeat the same for every field)
Definition for onInputChange():
const onInputChange = e =>{ console.log(e.target.value); setBook({...book,[e.target.name]:e.target.value}) }
<div class="form-group"> <label for="exampleInputEmail1">Book Name</label> <input type="text" class="form-control" name="bookName" placeholder="Enter Here" value={bookName} onChange={(e) =>onInputChange(e)} /> </div>
- Now, call the FormHandle() method to submit a form.
const FormHandle = e =>{ e.preventDefault(); addDataToServer(book) console.log(book) }
- Define the addDataToServer(book) method and use the Axios library to make an HTTP request to the backend.
const addDataToServer=(data) =>{ axios.post("http://localhost:8889/books",data).then( (response)=>{ console.log(response); alert("Book Added Successfully"); },(error)=>{ console.log(error); alert("Operation failed"); } ); }
Now, add the AddBookComponent.js into App.js
import logo from './logo.svg'; import './App.css'; import AddBookComponent from './components/AddBookComponent'; function App() { return ( <div className="App"> <AddBookComponent/> </div> ); } export default App;
Run the React JS app by going to the terminal and enter the following command
D:\Job Stuff\My_Study\React JS\book-frontend> npm start
At localhost:3000 you will be able to see the following output.
In this way, we can add a record in react JS by using the spring boot application at the backend.
ReactJs and Spring boot Application examples
https://codebun.com/edit-and-update-records-in-react-js-using-spring-boot-and-mysql/
https://codebun.com/delete-record-from-a-table-in-react-js-spring-boot-and-mysql/
https://codebun.com/search-record-from-a-table-in-react-js-spring-boot-and-mysql/
https://codebun.com/how-to-create-a-pagination-in-react-js-and-spring-boot/
https://codebun.com/how-to-create-spring-boot-and-reactjs-application/