In this tutorial, we will learn how to build a full stack CRUD App example using Spring Boot, React and MongoDB. The back-end server uses Spring Boot with Spring Web MVC for REST APIs and Spring Data MongoDB. The front-end side will be made with React, React Router, Axios & Bootstrap.
Related Post:
– Spring Boot + React Typescript example
– React + Spring Boot: Pagination example
– Spring Boot + React: Login example with JWT Authentication & Spring Security
– React Upload/Download Files to/from Spring Boot Rest Apis
Run both projects in one place:
How to integrate React.js with Spring Boot
Contents
Spring Boot, React, MongoDB example Overview
We will build a full-stack Tutorial Application in that:
- Each Tutorial has id, title, description, published status.
- We can create, retrieve, update, delete Tutorials.
- We can also find Tutorials by title.
– Create a Tutorial:
– Retrieve all items:
– Click on Edit button to view a Tutorial:
On this Page, you can:
- change status to Published using Publish button
- remove the Tutorial from Database using Delete button
- update the Tutorial details on Database with Update button
– Search Tutorials by title:
– Check MongoDB Database for all items:
Spring Boot, React and MongoDB Architecture
We’re gonna build the system with following architecture:
– Spring Boot exports REST Apis using Spring Web MVC & interacts with MongoDB Database using Spring Data MongoDB
– React Client sends HTTP Requests and retrieve HTTP Responses using axios, shows data on the components. We also use React Router for navigating to pages.
Spring Boot Back-end
Overview
These are APIs that Spring Boot App will export:
Methods | Urls | Actions |
---|---|---|
POST | /api/tutorials | create new Tutorial |
GET | /api/tutorials | retrieve all Tutorials |
GET | /api/tutorials/:id | retrieve a Tutorial by :id |
PUT | /api/tutorials/:id | update a Tutorial by :id |
DELETE | /api/tutorials/:id | delete a Tutorial by :id |
DELETE | /api/tutorials | delete all Tutorials |
GET | /api/tutorials?title=[keyword] | find all Tutorials which title contains keyword |
We make CRUD operations & finder methods with Spring Data MongoDB’s MongoRepository
.
Technology
- Java 17 / 11 / 8
- Spring Boot 3 / 2 (with Spring Web MVC, Spring Data MongoDB)
- MongoDB
- Maven 3.6.1
Project Structure
Tutorial
data model class corresponds to entity and table tutorials.TutorialRepository
is an interface that extends MongoRepository for CRUD methods and custom finder methods. It will be autowired inTutorialController
.TutorialController
is a RestController which has request mapping methods for RESTful requests such as: getAllTutorials, createTutorial, updateTutorial, deleteTutorial, findByPublished…- Configuration for Spring Data MongoDB is in application.properties.
- pom.xml contains dependencies for Spring Boot Web MVC and Spring Data MongoDB.
Implementation
Create & Setup Spring Boot project
Use Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project.
Then open pom.xml and add these dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Configure Spring Data MongoDB
Under src/main/resources folder, open application.properties and add following lines.
spring.data.mongodb.database=bezkoder_db
spring.data.mongodb.port=27017
Define Data Model
Our Data model is Tutorial with four fields: id, title, description, published.
In model package, we define Tutorial
class.
model/Tutorial.java
package com.bezkoder.spring.data.mongodb.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "tutorials")
public class Tutorial {
@Id
private String id;
private String title;
private String description;
private boolean published;
...
}
@Document
annotation helps us override the collection name by “tutorials”.
Create Repository Interface
Let’s create a repository to interact with Tutorials from the database.
In repository package, create TutorialRepository
interface that extends MongoRepository
.
repository/TutorialRepository.java
package com.bezkoder.spring.data.mongodb.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.bezkoder.spring.data.mongodb.model.Tutorial;
public interface TutorialRepository extends MongoRepository<Tutorial, String> {
List<Tutorial> findByTitleContaining(String title);
List<Tutorial> findByPublished(boolean published);
}
Now we can use MongoRepository’s methods: save()
, findOne()
, findById()
, findAll()
, count()
, delete()
, deleteById()
… without implementing these methods.
We also define custom finder methods:
– findByTitleContaining()
: returns all Tutorials which title contains input title
.
– findByPublished()
: returns all Tutorials with published
having value as input published
.
The implementation is plugged in by Spring Data MongoDB automatically.
Create Spring Rest APIs Controller
Finally, we create a controller that provides APIs for creating, retrieving, updating, deleting and finding Tutorials.
controller/TutorialController.java
package com.bezkoder.spring.data.mongodb.controller;
...
@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class TutorialController {
@Autowired
TutorialRepository tutorialRepository;
@GetMapping("/tutorials")
public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
}
@GetMapping("/tutorials/{id}")
public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") String id) {
}
@PostMapping("/tutorials")
public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
}
@PutMapping("/tutorials/{id}")
public ResponseEntity<Tutorial> updateTutorial(@PathVariable("id") String id, @RequestBody Tutorial tutorial) {
}
@DeleteMapping("/tutorials/{id}")
public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") String id) {
}
@DeleteMapping("/tutorials")
public ResponseEntity<HttpStatus> deleteAllTutorials() {
}
@GetMapping("/tutorials/published")
public ResponseEntity<List<Tutorial>> findByPublished() {
}
}
– @CrossOrigin
is for configuring allowed origins.
– @RestController
annotation is used to define a controller and to indicate that the return value of the methods should be be bound to the web response body.
– @RequestMapping("/api")
declares that all Apis’ url in the controller will start with /api
.
– We use @Autowired
to inject TutorialRepository
bean to local variable.
You can continue with step by step to implement this Spring Boot Server in the post:
Spring Boot with MongoDB CRUD example using Spring Data
Or Reactive Rest API: Spring Boot, MongoDB, Reactive CRUD example
Run Spring Boot Server
Run Spring Boot application with Maven command: mvn spring-boot:run
.
React.js Front-end
Overview
– The App
component is a container with React Router
. It has navbar
that links to routes paths.
– TutorialsList
component gets and displays Tutorials.
– Tutorial
component has form for editing Tutorial’s details based on :id
.
– AddTutorial
component has form for submission new Tutorial.
– These Components call TutorialDataService
methods which use axios
to make HTTP requests and receive responses.
Or you can use React with Redux:
More details at: React Redux CRUD App example with Rest API
Technology
- React 18/17
- react-router-dom 6
- axios 0.27.2
- bootstrap 4
Project Structure
– package.json contains 4 main modules: react
, react-router-dom
, axios
& bootstrap
.
– App
is the container that has Router
& navbar.
– There are 3 components: TutorialsList
, Tutorial
, AddTutorial
.
– http-common.js initializes axios with HTTP base Url and headers.
– TutorialDataService
has methods for sending HTTP requests to the Apis.
– .env configures port for this React CRUD App.
For Typescript version:
Please visit:
React Typescript CRUD example with Web API
Implementation
Setup React.js Project
Open cmd at the folder you want to save Project folder, run command:
npx create-react-app react-crud
After the process is done. We create additional folders and files like the following tree:
public
src
components
add-tutorial.component.js
tutorial.component.js
tutorials-list.component.js
services
tutorial.service.js
App.css
App.js
index.js
package.json
Import Bootstrap to React CRUD App
Run command: npm install bootstrap
.
Open src/App.js and modify the code inside it as following-
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
class App extends Component {
render() {
// ...
}
}
export default App;
Add React Router to React CRUD App
– Run the command: npm install react-router-dom
.
– Open src/index.js and wrap App
component by BrowserRouter
object.
import React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
const container = document.getElementById("root");
const root = createRoot(container);
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
Open src/App.js, this App
component is the root container for our application, it will contain a navbar
, and also, a Routes
object with several Route
. Each Route
points to a React Component.
import React, { Component } from "react";
...
class App extends Component {
render() {
return (
<div>
<nav className="navbar navbar-expand navbar-dark bg-dark">
<a href="/tutorials" className="navbar-brand">
bezKoder
</a>
<div className="navbar-nav mr-auto">
<li className="nav-item">
<Link to={"/tutorials"} className="nav-link">
Tutorials
</Link>
</li>
<li className="nav-item">
<Link to={"/add"} className="nav-link">
Add
</Link>
</li>
</div>
</nav>
<div className="container mt-3">
<Routes>
<Route path="/" element={<TutorialsList/>} />
<Route path="/tutorials" element={<TutorialsList/>} />
<Route path="/add" element={<AddTutorial/>} />
<Route path="/tutorials/:id" element={<Tutorial/>} />
</Routes>
</div>
</div>
);
}
}
export default App;
Initialize Axios for React CRUD HTTP Client
Let’s install axios with command: npm install axios
.
Under src folder, we create http-common.js file with following code:
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8080/api",
headers: {
"Content-type": "application/json"
}
});
You can change the baseURL
that depends on REST APIs url that your Server configures.
Create Data Service
In this step, we’re gonna create a service that uses axios object above to send HTTP requests.
services/tutorial.service.js
import http from "../http-common";
class TutorialDataService {
getAll() {
return http.get("/tutorials");
}
get(id) {
return http.get(`/tutorials/${id}`);
}
create(data) {
return http.post("/tutorials", data);
}
update(id, data) {
return http.put(`/tutorials/${id}`, data);
}
delete(id) {
return http.delete(`/tutorials/${id}`);
}
deleteAll() {
return http.delete(`/tutorials`);
}
findByTitle(title) {
return http.get(`/tutorials?title=${title}`);
}
}
export default new TutorialDataService();
We call axios get
, post
, put
, delete
method corresponding to HTTP Requests: GET, POST, PUT, DELETE to make CRUD Operations.
You can continue with step by step to implement this React App in the post:
– React.js CRUD example to consume Web API
– or React Hooks CRUD example to consume Web API
Using React with Redux:
– React Redux CRUD example with Rest API
– React Hooks + Redux: CRUD example with Rest API
For Typescript version:
React Typescript CRUD example to consume Web API
Run React CRUD App
You can run our App with command: npm start
.
If the process is successful, open Browser with Url: http://localhost:8081/
and check it.
Further Reading
Source Code
You can find Github source code for this tutorial at: Spring Boot and React Project Github
Conclusion
Now we have an overview of our Spring Boot React MongoDB CRUD example.
We also take a look at client-server architecture for REST API using Spring Web MVC & Spring Data MongoDB, as well as React project structure for building a front-end app to make HTTP requests and consume responses.
Next tutorials show you more details about how to implement the system (including source code):
– Back-end / Back-end with Reactive API
– Front-end:
- Using React Components
- Using React Typescript Components
- Using React Redux
- Using React Hooks
- Using React Hooks + Redux
- Using React with Material UI
You will want to know how to run both projects in one place:
How to integrate React.js with Spring Boot
Or Pagination:
– React Pagination with API using Material-UI
– Spring Boot MongoDB Pagination example with Spring Data
Using Typescript:
Spring Boot + React Typescript example
Happy learning, see you again!
Source Code
You can find Github source code for this tutorial at: Spring Boot and React Project Github
Thank you for writing the tutorial. I truly appreciate your efforts and I am waiting for your next write ups thanks once again.
Hey man! This is an excellent tutorial and it helped me a ton. I’m trying to take it one step further and deploy the project I built inspired by this tutorial to Heroku, but I’m having a hell of a time connecting the backend and frontend on Heroku.
Works great locally but once deployed I can’t seem to figure out how to connect the two outside of localhost ports. Do you have any advice or tips on how to get the two working together on Heroku?
Thanks!
i did’nt find the source code for the springboot react, mongo crud tutorial
Hi, you can find Github source code in the tutorials that I mentioned in Conclusion section 🙂
This tutorial API can be done with Java 11 or I’ll get troubles with it?
Hi, you can try it with Java 11. I’ve not tested yet.
If you have any problem, please comment here 🙂
Where can I find source code for this tutorial?
Hi, please visit the next tutorials in Conclusion section.
Hi, Due to latest version for react-router-dom changed sintaxis, the followin error occur when try start the proyect,
“./src/App.js
Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’.”
Could you help me to solve this in the code ? Thanks
Hi, the tutorial uses
react-router-dom
v5.In
react-router-dom
v6,Switch
is replaced byRoutes
. You need to update:to:
You also need to update the Route declaration from:
to:
(Not need to use
exact
in Route declaration)