Spring JPA + MySQL + AngularJS example | Spring Boot

In this tutorial, JavaSampleApproach shows you a Spring Boot example that uses Spring JPA to interact with MySQL and AngularJS as a front-end technology to make request and receive response.

Related Posts:
How to use Spring JPA with MySQL | Spring Boot
How to integrate Http Angularjs with Spring MVC | Spring Boot
Angular 4 + Spring JPA + MySQL example | Angular 4 Http Client – Spring Boot RestApi Server

I. Overview

1. Goal

spring-jpa-mysql-angularjs-goal

We’ll build a Spring Boot Application in that:
REST Service provides interface for interacting with Customer Database (MySQL) using Spring JPA.
– By using AngularJS to make HTTP request to REST Service and receive response, UI can save Customer Data (id, firstName, lastName), retrieves and displays:
+ All Customers in database.
+ Customer Data by customerId.
+ Customers List by lastName.

2. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.4.RELEASE
– Spring Boot: 1.5.4.RELEASE

3. Project Structure

spring-jpa-mysql-angularjs-project-structure

Our Application has 2 main parts: REST Service & UI
REST Service:
+ Customer Class corresponds to entity and table customer, it should be implemented Serializable.
+ CustomerRepository is an interface extends CrudRepository, will be autowired in CustomerController for implementing repository methods and custom finder methods.
+ CustomerController is a REST Controller which has request mapping methods for RESTful requests such as:
/postcustomer, /findall, /customer/{id}, /findByLastName.
+ Configuration for Spring Datasource and Spring JPA properties in application.properties.
+ Response class defines structure for returned data of HTTP GET.

To understand deeply the code about JPA that uses in this example, please visit:
How to use Spring JPA with MySQL | Spring Boot

UI: uses AngularJS for HTTP POST/GET requests:
+ home.jsp contains elements for POST/GET request and display results.
+ controller() and $http.get()/$http.post() methods in angular.js Javascript file.
+ WebController maps url to home.jsp page.

Simpler example that uses AngularJS HTTP POST/GET:
How to integrate Http Angularjs with Spring MVC | Spring Boot

– Configuration for JSP page and static resources in application.properties
– Dependencies for Spring JPA, WEB MVC, MySQL, Tomcat in pom.xml

To know how to make application work with JSP page and static resources, please visit:
How to start with JSP page and static resource in Spring Boot

II. Practice

1. Create Spring Boot project

– Using Spring Tool Suite/Eclipse to create Project (WAR packaging), ServletInitializer and SpringBootApplication class will be created automatically.
– Add Dependencies to pom.xml file:


	org.springframework.boot
	spring-boot-starter-data-jpa



	org.springframework.boot
	spring-boot-starter-web



	mysql
	mysql-connector-java
	runtime



	org.springframework.boot
	spring-boot-starter-tomcat
	provided



	org.apache.tomcat.embed
	tomcat-embed-jasper
	provided

2. Create Data Model Class
package com.javasampleapproach.angularjpamysql.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer implements Serializable {

	private static final long serialVersionUID = -3009157732242241606L;
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(name = "firstname")
	private String firstName;

	@Column(name = "lastname")
	private String lastName;

	protected Customer() {
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Customer(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
	}
}
3. Create Message Model Class
package com.javasampleapproach.angularjpamysql.message;

public class Response {
	private String status;
	private Object data;

	public Response() {

	}

	public Response(String status, Object data) {
		this.status = status;
		this.data = data;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
}
4. Create Repository Class
package com.javasampleapproach.angularjpamysql.repo;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.javasampleapproach.angularjpamysql.model.Customer;

public interface CustomerRepository extends CrudRepository {
	List findByLastName(String lastName);
}
5. Create Controller Classes
package com.javasampleapproach.angularjpamysql.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.angularjpamysql.message.Response;
import com.javasampleapproach.angularjpamysql.model.Customer;
import com.javasampleapproach.angularjpamysql.repo.CustomerRepository;

@RestController
public class CustomerController {

	@Autowired
	CustomerRepository repository;

	@RequestMapping(value = "/postcustomer", method = RequestMethod.POST)
	public void postCustomer(@RequestBody Customer customer) {

		repository.save(new Customer(customer.getFirstName(), customer.getLastName()));
	}

	@RequestMapping("/findall")
	public Response findAll() {

		Iterable customers = repository.findAll();

		return new Response("Done", customers);
	}

	@RequestMapping("/customer/{id}")
	public Response findCustomerById(@PathVariable("id") long id) {

		Customer customer = repository.findOne(id);

		return new Response("Done", customer);
	}

	@RequestMapping("/findbylastname")
	public Response findByLastName(@RequestParam("lastName") String lastName) {

		List customers = repository.findByLastName(lastName);

		return new Response("Done", customers);
	}
}
package com.javasampleapproach.angularjpamysql.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class WebController {

	@RequestMapping("/")
	ModelAndView home(ModelAndView modelAndView) {

		modelAndView.setViewName("home");

		return modelAndView;
	}
}
6. Configuration for Datasource, JPA, JSP page, resources

Add these lines to application.properties file (assume that you use testdb database with username root and password 123456:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.generate-ddl=true

spring.mvc.view.prefix = /WEB-INF/jsps/
spring.mvc.view.suffix = .jsp
7. Add JSP Page and Javascript File

Under src/main/webapp/WEB-INF/jsps folder, add:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>




Spring Boot Example

%MINIFYHTML3c7159109765fbc3f6473de75f1e5e5b14%%MINIFYHTML3c7159109765fbc3f6473de75f1e5e5b15%


	

AngularJS - Spring JPA - MySQL

%MINIFYHTML3c7159109765fbc3f6473de75f1e5e5b16%%MINIFYHTML3c7159109765fbc3f6473de75f1e5e5b17%

{{postResultMessage}}

All Customers

  • Customer {{$index}}
    Id: {{customer.id}}
    First Name: {{customer.firstName}}
    Last Name: {{customer.lastName}}

{{getResultMessage}}

Customer by ID


Id: {{customer.data.id}}
First Name: {{customer.data.firstName}}
Last Name: {{customer.data.lastName}}

{{getResultMessage}}

Customers by LastName


  • Customer {{$index}}
    Id: {{customer.id}}
    First Name: {{customer.firstName}}
    Last Name: {{customer.lastName}}

{{getResultMessage}}

%MINIFYHTML3c7159109765fbc3f6473de75f1e5e5b18%

Under src/main/webapp/js folder, add:

var app = angular.module('app', []);

app.controller('postController', function($scope, $http, $location) {
	$scope.submitForm = function(){
		var url = $location.absUrl() + "postcustomer";
		
		var config = {
                headers : {
                    'Content-Type': 'application/json;charset=utf-8;'
                }
        }
		
		var data = {
            firstName: $scope.firstname,
            lastName: $scope.lastname
        };
		
		
		$http.post(url, data, config).then(function (response) {
			$scope.postResultMessage = "Sucessful!";
		}, function (response) {
			$scope.postResultMessage = "Fail!";
		});
		
		$scope.firstname = "";
		$scope.lastname = "";
	}
});

app.controller('getallcustomersController', function($scope, $http, $location) {
	
	$scope.showAllCustomers = false;

	$scope.getAllCustomers = function() {
		var url = $location.absUrl() + "findall";

		var config = {
			headers : {
				'Content-Type' : 'application/json;charset=utf-8;'
			}
		}

		$http.get(url, config).then(function(response) {

			if (response.data.status == "Done") {
				$scope.allcustomers = response.data;
				$scope.showAllCustomers = true;

			} else {
				$scope.getResultMessage = "get All Customers Data Error!";
			}

		}, function(response) {
			$scope.getResultMessage = "Fail!";
		});

	}
});

app.controller('getcustomerController', function($scope, $http, $location) {
	
	$scope.showCustomer = false;
	
	$scope.getCustomer = function() {
		var url = $location.absUrl() + "customer/" + $scope.customerId;

		var config = {
			headers : {
				'Content-Type' : 'application/json;charset=utf-8;'
			}
		}

		$http.get(url, config).then(function(response) {

			if (response.data.status == "Done") {
				$scope.customer = response.data;
				$scope.showCustomer = true;

			} else {
				$scope.getResultMessage = "Customer Data Error!";
			}

		}, function(response) {
			$scope.getResultMessage = "Fail!";
		});

	}
});

app.controller('getcustomersbylastnameController', function($scope, $http, $location) {
	
	$scope.showCustomersByLastName = false;
	
	$scope.getCustomersByLastName = function() {
		var url = $location.absUrl() + "findbylastname";

		var config = {
			headers : {	'Content-Type' : 'application/json;charset=utf-8;' },
		
			params: { 'lastName' : $scope.customerLastName }
		}

		$http.get(url, config).then(function(response) {

			if (response.data.status == "Done") {
				$scope.allcustomersbylastname = response.data;
				$scope.showCustomersByLastName = true;

			} else {
				$scope.getResultMessage = "Customer Data Error!";
			}

		}, function(response) {
			$scope.getResultMessage = "Fail!";
		});

	}
});
8. Run & Check Result

– Config maven build:
clean install
– Run project with mode Spring Boot App.
– Open Browser, enter URL:
http://localhost:8080/
spring-jpa-mysql-angularjs-request

– Fill Form to Post Customer Data & press Submit button.
Then press Get All Customers button, find Customer by Id, find Customers by Last Name:
spring-jpa-mysql-angularjs-results

– Open MySQL WorkBench to check database:
spring-jpa-mysql-angularjs-database

III. Source Code

SpringJPAMySQLAngularJS



By grokonez | June 19, 2017.

Last updated on February 6, 2020.



Related Posts


8 thoughts on “Spring JPA + MySQL + AngularJS example | Spring Boot”

  1. Great tutorial. Great Explanation.
    Suggestion:- Instead of repository.save(new Customer(customer.getFirstName(), customer.getLastName())); we can use
    repository.save(customer); inside the CustoemrController class.
    THnk you. Keep it up.

Got Something To Say:

Your email address will not be published. Required fields are marked *

*