Vue JS + Spring Boot + MySQL Example

In this tutorial, we will learn how to build a simple Full Stack application using Vue JS as frontend, Spring boot as backend and we use MySQL database.

Vue JS is a progressive framework for building user interfaces (UI) on the front end.

Spring Boot is a very popular Java framework for building RESTful web services and microservices.

In this tutorial, we will use the Axios HTTP library to make HTTP Get REST API call.

Tools and technologies used

Backend:
  • Spring Boot
  • Spring MVC
  • Spring Data JPA (Hibernate)
  • Eclipse STS
  • MySQL Database
Frontend:
  • Vue 3
  • Axios
  • Bootstrap 4
  • VS Code

What we will build?

We will build two projects:
  1. springboot-backend - Develop and expose REST APIs
  2. vue-frontend - Consume REST APIs

1. Develop Spring boot application - Backend

Let's begin with creating a Spring boot application and build a simple REST API.

1. Create a Spring Boot Application

There are many ways to create a Spring Boot application. You can refer to the below articles to create a Spring Boot application.

2. Add maven dependencies

Here is a complete pom.xml file for your reference:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.0.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>net.javaguides</groupId>
	<artifactId>springboot-backend</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>springboot-backend</name>
	<description>Spring Boot backend application</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<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.mysql</groupId>
		       <artifactId>mysql-connector-j</artifactId>
		       <scope>runtime</scope>
	        </dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

3. MySQL Database Configuration

First, you need to create a database in MySQL server with the following command:
create database demo

Now, let's open the application.properties file in Spring boot project and add MySQL database details to connect to your MySQL database. 
Here is the application.properties file:
spring.datasource.url = jdbc:mysql://localhost:3306/demo?useSSL=false
spring.datasource.username = root
spring.datasource.password = root


## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
Make sure that you will change the above database configuration such as JDBC URL, username, and password as per your environment.
Hibernate will automatically create database tables so you only need to manually create the database and configure an application.properties file.

4. Create JPA Entity - Employee.java

Let's create a new package called entity inside net.javaguides.springboot package and then create the Employee class inside the entity package with the following contents -
package net.javaguides.springboot.entity;

import lombok.*;

import jakarta.persistence.*;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
@Table(name = "employees")
public class Employee {

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

    @Column(name = "first_name", nullable = false)
    private String firstName;

    @Column(name = "last_name")
    private String lastName;
    private String email;

}

5. Create Spring Data JPA Repository - EmployeeRepository.java

Now, we gonna create a Spring Data JPA repository to talk with the MySQL database. 
Let's create a new package called repository inside net.javaguides.springboot package and then create the following EmployeeRepository interface inside the repository package:
package net.javaguides.springboot.repository;

import net.javaguides.springboot.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}

6. Spring Controller with REST API - /api/employees

Let's create a new package called controller inside net.javaguides.springboot package and then create the following EmployeeController class inside the controller package with the following contents -
package net.javaguides.springboot.controller;

import net.javaguides.springboot.entity.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
@CrossOrigin("http://localhost:3000/")
public class EmployeeController {

    @Autowired
    private EmployeeRepository employeeRepository;

    @GetMapping("/employees")
    public List<Employee> fetchEmployees(){
        return employeeRepository.findAll();
    }
}
Note that we have added the below code to avoid CORS issues:
@CrossOrigin(origins = "http://localhost:3000")

7. Run Spring Boot Application and Test Rest API

Let's insert a few records in the employees table while application startup.
package net.javaguides.springboot;

import net.javaguides.springboot.entity.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootBackendApplication implements CommandLineRunner {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootBackendApplication.class, args);
	}

	@Autowired
	private EmployeeRepository employeeRepository;

	@Override
	public void run(String... args) throws Exception {

		Employee employee1 = Employee.builder()
				.firstName("Ramesh")
				.lastName("Fadatare")
				.email("ramesh@gmail.com")
				.build();

		Employee employee2 = Employee.builder()
				.firstName("Tony")
				.lastName("Stark")
				.email("tony@gmail.com")
				.build();

		Employee employee3 = Employee.builder()
				.firstName("John")
				.lastName("Cena")
				.email("cena@gmail.com")
				.build();

		employeeRepository.save(employee1);
		employeeRepository.save(employee2);
		employeeRepository.save(employee3);
	}
}
Let's run this spring boot application from IDE -> Right-click -> Run As -> Java Application:

Hit this "http://localhost:8080/api/employees" link in a browser will popular list of employees as JSON:

[
   {
      "id":1,
      "firstName":"Ramesh",
      "lastName":"Fadatare",
      "email":"ramesh@gmail.com"
   },
   {
      "id":2,
      "firstName":"Tony",
      "lastName":"Stark",
      "email":"tony@gmail.com"
   },
   {
      "id":3,
      "firstName":"John",
      "lastName":"Cena",
      "email":"cena@gmail.com"
   }
]

Build Vue JS Frontend Application

Let's go ahead and create a Vue application to consume /api/employees REST API.
We will use Vue 3 and Axios HTTP library to make a REST API call in the Vue application. We will use VS Code IDE to build the Vue application.

1. Vue JS Project Setup

To install and use the Vue CLI as well as run the Vue application server, you'll need the Node.js JavaScript runtime and npm (the Node.js package manager) installed. npm is included with Node.js which you can install from Node.js downloads.

To test that you have Node.js and npm correctly installed on your machine, you can type

node --version 
npm --version

To install the vue/cli, in a terminal or command prompt type the below command(Note: open cmd using an administrator in Windows. For Mac/Linux, use the sudo before below command to give permission):

npm install -g @vue/cli

This may take a few minutes to install. You can now create a new Vue.js application by typing:

vue create vue-frontend

where vue-frontend is the name of the folder for your application.


Let's quickly run our Vue application by navigating to the new folder and typing npm run serve to start the webserver and open the application in a browser:

cd vue-frontend
npm run serve

2. Install Vetur extension in VS Code

Let's install the Vetur extension in VS code, this extension supplies Vue.js language features (syntax highlighting, IntelliSense, snippets, formatting) to VS Code.

3. Add Bootstrap to Vue App

Go to terminal and navigate to your project's folder, and run the following command:
npm install bootstrap —save
npm install --save @popperjs/core
After installing the bootstrap package, you will need to import it into your Vue app entry file.
import Vue from 'vue'
import App from './App.vue'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

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

4. Vue Service Class - REST API Call

For our API calls, we will be using Axios. Below is the npm command to install Axios.
npm add axios
Let's create a services folder within an src folder. Within the services folder, create an EmployeeServce.js class with the following code to make our HTTP REST call via Axios. 
import axios from 'axios';

const EMPLOYEE_API_BASE_URL = 'http://localhost:8080/api/employees';

class EmployeeService{

    getEmployees(){
        return axios.get(EMPLOYEE_API_BASE_URL);
    }
}

export default new EmployeeService();
Note that our backend Employee endpoint is available at http://localhost:8080/api/employees.
Make sure that you create an object of EmployeeService class export it as:
export default new EmployeeService();

5. Create Vue Component - src/components/Employees.vue

Let's create a components folder within the src folder and create an Employees.vue file with the following code to it.
<template>
    <div class = "container">
            
            <h1 class = "text-center"> Employees List</h1>

            <table class = "table table-striped">
                <thead>
                    <tr>
                        <th> Employee Id</th>
                        <th> Employee First Name</th>
                        <th> Employee Last</th>
                        <th> Employee Email</th>
                    </tr>

                </thead>
                <tbody>
                    <tr v-for="employee in employees" v-bind:key="employee.id">
                        <td> {{employee.id }}</td>
                        <td> {{employee.firstName }}</td>
                        <td> {{employee.lastName}}</td>    
                        <td> {{employee.email}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
</template>

<script>

import EmployeeService from '../services/EmployeeService';

export default {
    name: 'Employees',
    data(){
        return {
            employees: []
        }
    },
    methods: {
        getEmployees(){
            EmployeeService.getEmployees().then((response) => {
                this.employees = response.data;   
            });
        }
    },
    created() {
        this.getEmployees();
    }
}

</script>
Let's understand the above code step by step:
One of the first things you would need to understand about Vue is the concept of the component. Vue component is consists of template, script, and style.
  • template is nothing but the HTML template with Vue directives
  • script is javascript code to write for the Vue module
  • style is CSS for the Vue module
created() - Vue defines a component lifecycle. created will be called as soon as the component is mounted. We are calling getEmployees() as soon as a component is mounted:
created() {
        this.getEmployees();
}
methods: { getEmployees() {}} - Any method in a Vue component should be under methods. 
methods: {
        getEmployees(){
            EmployeeService.getEmployees().then((response) => {
                this.employees = response.data;   
            });
        }
},
EmployeeService.getEmployees().then - This would make the call to the REST API. You can define how to process the response in the then method:
            EmployeeService.getEmployees().then((response) => {
                this.employees = response.data;   
            });

6. App Component - src/App.vue

Let’s update the App.vue to display the Employees component.

<template>
  <div id="app">
    <Employees />
  </div>
</template>

<script>
import Employees from './components/Employees.vue'

export default {
  name: 'App',
  components: {
    Employees
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

7. Run Vue Application

Open a terminal and move to the project folder and type the below command to run the Vue application:
npm run serve
Runs the app in development mode. Open http://localhost:8081 to view it in the browser.


Conclusion

In this tutorial, we have learned how to build a simple Full Stack application using Spring boot as backend and Vue JS as frontend.

Comments