[Full-stack] Spring Boot + Vue.js: CRUD example

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

Related Posts:
Spring Boot + Vue.js: Authentication with JWT & Spring Security Example
Spring Boot + Vue.js + MySQL: CRUD example
Spring Boot + Vue.js + PostgreSQL: CRUD example
Spring Boot + Vue.js + MongoDB: CRUD example

More Practice: Vue + Spring Boot: File Upload example

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

Other Databases:

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


Spring Boot Vue.js 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 Tutorial:

spring-boot-vue-js-crud-example-demo-0

– Show all Tutorials:

spring-boot-vue-js-crud-example-demo-1

– Click on Edit button to update a Tutorial:

spring-boot-vue-js-crud-example-demo-2

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:

spring-boot-vue-js-crud-example-demo-3

Spring Boot Vue.js Architecture

Now look at the application architecture we will build:

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

– Spring Boot exports REST Apis using Spring Web MVC & interacts with embedded H2 Database using Spring JPA.
– 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.

You can also find the Spring Restful Apis that works with other databases here:
Spring JPA + PostgreSQL
Spring JPA + MySQL
Spring JPA + SQL Server
Spring Data + MongoDB
Spring JPA + Oracle
Spring Data + Cassandra

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 JPA’s JpaRepository.
– The database will be H2 Database (in memory or on disk) by configuring project dependency & datasource.

Technology

  • Java 17 /11 / 8
  • Spring Boot 3 / 2 (with Spring Web MVC, Spring Data JPA)
  • H2 Database
  • Maven

Project Structure

spring-boot-vue-js-crud-example-spring-server-project-structure

Tutorial data model class corresponds to entity and table tutorials.
TutorialRepository is an interface that extends JpaRepository 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 Datasource, JPA & Hibernate in application.properties.
pom.xml contains dependencies for Spring Boot and H2 Database.

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-data-jpa</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>

Configure Spring Datasource, JPA, Hibernate

Under src/main/resources folder, open application.properties and write these lines.

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
 
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update

spring.h2.console.enabled=true
# default path: h2-console
spring.h2.console.path=/h2-ui
  • spring.datasource.url: jdbc:h2:mem for In-memory database and jdbc:h2:file for disk-based database.
  • spring.datasource.username & spring.datasource.password properties are the same as your database installation.
  • Spring Boot uses Hibernate for JPA implementation, we configure H2Dialect for H2 Database
  • spring.jpa.hibernate.ddl-auto is used for database initialization. We set the value to update value so that a table will be created in the database automatically corresponding to defined data model. Any change to the model will also trigger an update to the table. For production, this property should be validate.
  • spring.h2.console.enabled=true tells the Spring to start H2 Database administration tool and you can access this tool on the browser: http://localhost:8080/h2-console.
  • spring.h2.console.path=/h2-ui is for H2 console’s url, so the default url http://localhost:8080/h2-console will change to http://localhost:8080/h2-ui.

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.datajpa.model;

// import javax.persistence.*; // for Spring Boot 2
import jakarta.persistence.*; // for Spring Boot 3

@Entity
@Table(name = "tutorials")
public class Tutorial {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(name = "title")
	private String title;

	@Column(name = "description")
	private String description;

	@Column(name = "published")
	private boolean published;

	public Tutorial() {

	}

	...
}

@Entity annotation indicates that the class is a persistent Java class.
@Table annotation provides the table that maps this entity.
@Id annotation is for the primary key.
@GeneratedValue annotation is used to define generation strategy for the primary key. GenerationType.AUTO means Auto Increment field.
@Column annotation is used to define the column in database that maps annotated field.

Create Repository Interface

Let’s create a repository to interact with Tutorials from the database.
In repository package, create TutorialRepository interface that extends JpaRepository.

repository/TutorialRepository.java

package com.bezkoder.spring.datajpa.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.bezkoder.spring.datajpa.model.Tutorial;

public interface TutorialRepository extends JpaRepository<Tutorial, Long> {
  List<Tutorial> findByPublished(boolean published);
  List<Tutorial> findByTitleContaining(String title);
}

Now we can use JpaRepository’s methods: save(), findOne(), findById(), findAll(), count(), delete(), deleteById()… without implementing these methods.

We also define custom finder methods:
findByPublished(): returns all Tutorials with published having value as input published.
findByTitleContaining(): returns all Tutorials which title contains input title.

The implementation is plugged in by Spring Data JPA automatically.

You can modify this Repository:
– to work with Pagination, the instruction can be found at:
Spring Boot Pagination & Filter example | Spring JPA, Pageable
– or to sort/order by multiple fields with the tutorial:
Spring Data JPA Sort/Order by multiple Columns | Spring Boot

You also find way to write Unit Test for this JPA Repository at:
Spring Boot Unit Test for JPA Repositiory with @DataJpaTest

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.datajpa.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") long id) {
    ...
  }

  @PostMapping("/tutorials")
  public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
    ...
  }

  @PutMapping("/tutorials/{id}")
  public ResponseEntity<Tutorial> updateTutorial(@PathVariable("id") long id, @RequestBody Tutorial tutorial) {
    ...
  }

  @DeleteMapping("/tutorials/{id}")
  public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") long 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 one of the posts:
Spring Boot JPA + H2
Spring Boot JPA + MySQL
Spring Boot JPA + PostgreSQL

Run the Spring Boot Server

Run Spring Boot application with command: mvn spring-boot:run.

Vue.js Front-end

Overview

spring-boot-vue-js-crud-example-vue-client-overview

– 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-crud-example-vue-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 CRUD example when building a CRUD App with embedded H2 database.

We also take a look at client-server architecture for REST API using Spring Web MVC & Spring Data JPA, 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:

– 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

– Spring Restful Apis for other databases:

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

13 thoughts to “[Full-stack] Spring Boot + Vue.js: CRUD example”

  1. Thank you very much – Vue is just the best ❤️ Do you know bootify.io already? You get the Spring Boot MySQL + CRUD database in a minute. Cheers, Winf.

  2. Hello,
    How do you build them, how is the connection made? Hello,
    the explanations are good, but only separated projects, but why don’t you explain how you make the connection backend and frontend?

    1. Hi, the connection is established by API call and CORS configuration that you can find in the tutorials 🙂

  3. Best sample code and tutorial on the web. Very practical.
    Could you make some samples on how to deploy the springboot with vue to same web server, for example tomcat?

    1. Hi, I will write the tutorial you suggest when having time. Thank you for your comment 🙂

      1. Your tutorial is great. Kudos for job well done.
        Please why did you skip service layer in the tutorial. Is it that the service layer can be skipped without any problem on the application or that you left it for brevity?

        1. Hi, just for brevity 🙂
          People who want to use service layer can add it between controller & repository layer.

  4. I spend more than one hours to search for this Spring Boot + Vue fullstack tutorial.
    Thank you so much for this.

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