Prerequisites
Before we start, ensure you have the following:
- Java Development Kit (JDK) installed
- Apache Maven installed
- Node.js and npm installed
- MySQL installed and running
- An IDE (such as IntelliJ IDEA, Eclipse, or VS Code) installed
React JS + Spring Boot + MySQL Full-Stack Application Architecture
+--------------------------------------------------------+
| React Frontend App |
|--------------------------------------------------------|
| +--------------+ +----------------+ +------------+ |
| | Router | | Components | | Services | |
| +--------------+ +----------------+ +------------+ |
| |
| +-----------------------------+ |
| | Axios HTTP Library | |
| +-----------------------------+ |
+--------------------------------------------------------+
|
v
+-------------------------------------------------------+
| Spring Boot Backend App |
|-------------------------------------------------------|
| +-----------------------------+ |
| | Spring REST Controller | |
| +-----------------------------+ |
| |
| +--------+ +--------+ +------------+ |
| | Model | | Service| | DAO (Repo) | |
| +--------+ +--------+ +------------+ |
+-------------------------------------------------------+
|
v
+-----------------------------+
| MySQL Database |
+-----------------------------+
Explanation:
-
React Frontend App:
- Router: Manages routing and navigation within the application.
- Components: Represents the UI elements of the application.
- Services: Handles the business logic and data processing in the frontend.
- Axios HTTP Library: A promise-based HTTP client for making requests to the backend.
-
Spring Boot Backend App:
- Spring REST Controller: Handles incoming HTTP requests and defines endpoints.
- Model: Represents the data structure or entity.
- Service: Contains the business logic.
- DAO (Repository): Interacts with the database.
-
MySQL Database: Stores the application's data.
In this architecture, the React frontend app communicates with the Spring Boot backend app using Axios to make HTTP requests. The backend app processes these requests, interacts with the MySQL database, and sends responses back to the frontend app.
Step 1: Setting Up the Spring Boot Project
1.1 Create a Spring Boot Project
-
Open Spring Initializr:
- Go to Spring Initializr in your web browser.
-
Configure Project Metadata:
- Project: Maven Project
- Language: Java
- Spring Boot: Select the latest version of Spring Boot 3
- Group: com.example
- Artifact: spring-boot-react-mysql
- Name: spring-boot-react-mysql
- Description: Full Stack Application with Spring Boot and React using MySQL
- Package Name: com.example.springbootreactmysql
- Packaging: Jar
- Java Version: 17 (or your preferred version)
- Click
Next
.
-
Select Dependencies:
- On the
Dependencies
screen, select the dependencies you need:- Spring Web
- Spring Data JPA
- MySQL Driver
- Spring Boot DevTools
- Click
Next
.
- On the
-
Generate the Project:
- Click
Generate
to download the project zip file. - Extract the zip file to your desired location.
- Click
-
Open the Project in Your IDE:
- Open your IDE and import the project as a Maven project.
1.2 Update application.properties
Open the application.properties
file located in the src/main/resources
directory and add the following configuration:
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
Replace root
with your MySQL username and password, and testdb
with your database name.
1.3 Create the Product
Entity
In the com.example.springbootreactmysql.model
package, create a new Java class named Product
:
package com.example.springbootreactmysql.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
// Getters and Setters
}
1.4 Create the ProductRepository
Interface
In the com.example.springbootreactmysql.repository
package, create a new Java interface named ProductRepository
:
package com.example.springbootreactmysql.repository;
import com.example.springbootreactmysql.model.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
1.5 Create the ProductService
Class
In the com.example.springbootreactmysql.service
package, create a new Java class named ProductService
:
package com.example.springbootreactmysql.service;
import com.example.springbootreactmysql.model.Product;
import com.example.springbootreactmysql.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
private final ProductRepository productRepository;
@Autowired
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public List<Product> getAllProducts() {
return productRepository.findAll();
}
public Product saveProduct(Product product) {
return productRepository.save(product);
}
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}
}
1.6 Create the ProductController
Class
In the com.example.springbootreactmysql.controller
package, create a new Java class named ProductController
:
package com.example.springbootreactmysql.controller;
import com.example.springbootreactmysql.model.Product;
import com.example.springbootreactmysql.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductService productService;
@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@PostMapping
public Product saveProduct(@RequestBody Product product) {
return productService.saveProduct(product);
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}
}
Step 2: Creating the Frontend with React
2.1 Set Up React Project
-
Open a terminal and navigate to your workspace directory.
-
Create a new React project using Create React App:
npx create-react-app react-frontend
-
Navigate to the project directory:
cd react-frontend
2.2 Install Axios and Bootstrap
Install Axios to make HTTP requests and Bootstrap for styling:
npm install axios bootstrap
2.3 Create Components
Create the necessary components for displaying and managing products.
2.3.1 Create ProductService.js
Create a new file ProductService.js
in the src
directory to handle API requests for products:
import axios from 'axios';
const API_BASE_URL = "http://localhost:8080/products";
class ProductService {
getAllProducts() {
return axios.get(API_BASE_URL);
}
getProductById(productId) {
return axios.get(`${API_BASE_URL}/${productId}`);
}
createProduct(product) {
return axios.post(API_BASE_URL, product);
}
}
export default new ProductService();
2.3.2 Create ProductListComponent.js
Create a new file ProductListComponent.js
in the src/components
directory:
import React, { useEffect, useState } from 'react';
import ProductService from '../ProductService';
import 'bootstrap/dist/css/bootstrap.min.css';
const ProductListComponent = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
ProductService.getAllProducts().then((response) => {
setProducts(response.data);
});
}, []);
return (
<div className="container mt-5">
<h2>Products</h2>
<ul className="list-group">
{products.map(product => (
<li key={product.id} className="list-group-item">
{product.name} - ${product.price}
</li>
))}
</ul>
</div>
);
};
export default ProductListComponent;
2.3.3 Create AddProductComponent.js
Create a new file AddProductComponent.js
in the src/components
directory:
import React, { useState } from 'react';
import ProductService from '../ProductService';
import 'bootstrap/dist/css/bootstrap.min.css';
const AddProductComponent = () => {
const [name, setName] = useState('');
const [price, setPrice] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
const product = { name, price };
ProductService.createProduct(product).then(response => {
console.log(response.data);
});
};
return (
<div className="container mt-5">
<h2>Add Product</h2>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label>Product Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="form-group">
<label>Product Price</label>
<input
type="number"
className="form-control"
value={price}
onChange={(e) => setPrice(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary mt-3">Add</button>
</form>
</div>
);
};
export default AddProductComponent;
2.3.4 Create App.js
Modify the App.js
file to include routing for the components:
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import ProductListComponent from './components/ProductListComponent';
import AddProductComponent from './components/AddProductComponent';
import 'bootstrap/dist/css/bootstrap.min.css';
const App = () => {
return (
<Router>
<div className="container">
<Routes>
<Route path="/" element={<ProductListComponent />} />
<Route path="/add-product" element={<AddProductComponent />} />
</Routes>
</div>
</Router>
);
};
export default App;
2.3.5 Update index.js
Ensure the index.js
file is set up correctly:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Step 3: Running the Application
3.1 Run the Spring Boot Application
- Open the
SpringBootReactMysqlApplication
class in thesrc/main/java/com/example/springbootreactmysql
directory. - Click the green
Run
button in your IDE or use the terminal to run the application:./mvnw spring-boot:run
3.2 Run the React Application
-
Open a terminal and navigate to the
react-frontend
directory. -
Start the React application:
npm start
-
Open your web browser and navigate to
http://localhost:3000
.
You should see the list of products and be able to add new products using the form.
Conclusion
In this tutorial, we created a full-stack application using Spring Boot for the backend and React for the frontend, with MySQL as the database. We set up the backend to handle CRUD operations for products and created a frontend with React to display and manage products. This setup provides a solid foundation for developing more complex full-stack applications with React and Spring Boot.
Comments
Post a Comment