Spring Boot + Vue.js + MongoDB: CRUD example

In this tutorial, we will learn how to build a full stack example with Spring Boot + Vue.js + MongoDB CRUD Application. The back-end server uses Spring Boot with Spring Web MVC for REST Controller and Spring Data for interacting with MongoDB database. Front-end side is made with Vue, Vue Router & Bootstrap.

Related Post: Spring Boot + Vue.js: Authentication with JWT & Spring Security Example

More Practice: Vue + Spring Boot: File Upload example

Run both Project on same server/port:
How to integrate Vue.js with Spring Boot

Serverless with Firebase:
Vue Firebase Realtime Database: CRUD example
Vue Firestore: Build a CRUD App example


Spring Boot, Vue.js, MongoDB CRUD example

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.

The images below shows screenshots of our System.

– Add an object:

spring-boot-vue-js-mongodb-crud-example-create

– Show all objects:

spring-boot-vue-js-mongodb-crud-example-retrieve

– Click on Edit button to update the object:

spring-boot-vue-js-mongodb-crud-example-retrieve-one

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

spring-boot-vue-js-mongodb-crud-example-update

– Search Tutorials by title:

spring-boot-vue-js-mongodb-crud-example-find-by-field

– Check MongoDB tutorials collection:

spring-boot-vue-js-mongodb-crud-example-mongodb-collection

Spring Boot, Vue.js, MongoDB Architecture

This is the application architecture that we’re gonna build:

spring-boot-vue-js-mongodb-crud-example-architecture

– Spring Boot exports REST Apis using Spring Web MVC & interacts with MongoDB Database using Spring Data MongoDB.
– Vue Client sends HTTP Requests and retrieve HTTP Responses using axios, shows data on the components. We also use Vue Router for navigating to pages.

Spring Boot MongoDB 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’s MongoRepository.

Technology

  • Java 8
  • Spring Boot 2.2.4 (with Spring Web MVC, Spring Data MongoDB)
  • MongoDB
  • Maven 3.6.1

Project Structure

spring-boot-vue-js-mongodb-crud-example-server-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 in TutorialController.
  • 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.

Vue.js Front-end

Overview

spring-boot-vue-js-mongodb-crud-example-vue-components

– The App component is a container with router-view. 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.

Technology

  • vue: 2.6.10
  • vue-router: 3.1.3
  • axios: 0.19.0

If you want to use Vue 3 instead, please visit:
Vue 3 CRUD example with Axios & Vue Router

Project Structure

spring-boot-vue-js-mongodb-crud-example-client-project-structure

package.json contains 3 main modules: vue, vue-router, axios.
– There are 3 components: TutorialsList, Tutorial, AddTutorial.
router.js defines routes for each component.
http-common.js initializes axios with HTTP base Url and headers.
TutorialDataService has methods for sending HTTP requests to the Apis.
vue.config.js configures port for this Vue Client.

Implementation

Setup Vue.js Project

Open cmd at the folder you want to save Project folder, run command:
vue create vue-js-client-crud

You will see some options, choose default (babel, eslint).
After the process is done. We create new folders and files like the following tree:


public

index.html

src

components

AddTutorial.vue

Tutorial.vue

TutorialsList.vue

services

TutorialDataService.js

App.vue

main.js

package.json


Open public/index.html, add bootstrap inside <head> tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <title>vue-js-client-crud</title>
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
  </head>
  <body>
    ...
  </body>
</html>

Add Vue Router to Vue.js 2 CRUD App

– Run the command: npm install vue-router.

– In src folder, create router.js and define Router as following code:

import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

export default new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      alias: "/tutorials",
      name: "tutorials",
      component: () => import("./components/TutorialsList")
    },
    {
      path: "/tutorials/:id",
      name: "tutorial-details",
      component: () => import("./components/Tutorial")
    },
    {
      path: "/add",
      name: "add",
      component: () => import("./components/AddTutorial")
    }
  ]
});

– Open src/main.js, then import router:

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

Add Navbar and Router View to Vue.js 2 CRUD App

Let’s open src/App.vue, this App component is the root container for our application, it will contain a navbar.

<template>
  <div id="app">
    <nav class="navbar navbar-expand navbar-dark bg-dark">
      <router-link to="/" class="navbar-brand">bezKoder</router-link>
      <div class="navbar-nav mr-auto">
        <li class="nav-item">
          <router-link to="/tutorials" class="nav-link">Tutorials</router-link>
        </li>
        <li class="nav-item">
          <router-link to="/add" class="nav-link">Add</router-link>
        </li>
      </div>
    </nav>

    <div class="container mt-3">
      <router-view />
    </div>
  </div>
</template>

<script>
export default {
  name: "app"
};
</script>

Initialize Axios for Vue.js 2 CRUD HTTP Client

Now we’re gonna install axios with command: npm install axios.
Then, under src folder, we create http-common.js file like this:

import axios from "axios";

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

Remember to change the baseURL, it depends on REST APIs url that your Server configures.

Create Data Service

Our service will use axios from HTTP client above to send HTTP requests.

services/TutorialDataService.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();

Create Vue Components

As I’ve said before, we have 3 components corresponding to 3 routes defined in Vue Router.

  • Add new Item
  • List of items
  • Item details

You can continue with step by step to implement this Vue App in the post:
Vue.js CRUD App with Vue Router & Axios

Or using Vuetify: Vuetify data-table example with a CRUD App

vuetify-data-table-example-crud-app-retrieve-all

Run Vue.js Client

You can run our Vue App with command: npm run serve.
If the process is successful, open Browser with Url: http://localhost:8081/ and check it.

Conclusion

Now we have an overview of Spring Boot Vue.js MongoDB CRUD example when building a CRUD App that connects with MongoDB database.

We also take a look at client-server architecture for REST API using Spring Web MVC & Spring Data MongoDB, as well as Vue.js 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:
Back-end / Back-end with Reactive API
– Front-end:

Run both Project on same server/port:
How to integrate Vue.js with Spring Boot

If you want a Typescript version for the Vue App, it is here:
Vue Typescript CRUD Application to consume Web API example

Serverless with Firebase:
Vue Firebase Realtime Database: CRUD example
Vue Firestore: Build a CRUD App example

Happy learning, see you again!

Further Reading

Source Code

You can find Github source code for this tutorial at: Spring Boot with Vue.js Github

2 thoughts to “Spring Boot + Vue.js + MongoDB: CRUD example”

Comments are closed to reduce spam. If you have any question, please send me an email.