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
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
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.
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.
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
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:
<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>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> |
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<Customer, Long> { List<Customer> 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<Customer> 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<Customer> 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"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Spring Boot Example</title> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script> <script src="/js/angular.js"></script> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" /> </head> <body> <div class="container" ng-app="app"> <h1>AngularJS - Spring JPA - MySQL</h1> <div class="row"> <div ng-controller="postController" class="col-md-3"> <form name="customerForm" ng-submit="submitForm()"> <label>FirstName</label> <input type="text" name="firstname" class="form-control" ng-model="firstname" /> <label>LastName</label> <input type="text" name="lastname" class="form-control" ng-model="lastname" /> <button type="submit" class="btn btn-primary">Submit</button> </form> <p>{{postResultMessage}}</p> </div> </div> <div class="row"> <div ng-controller="getallcustomersController" class="col-md-3"> <h3>All Customers</h3> <button ng-click="getAllCustomers()">Get All Customers</button> <div ng-show="showAllCustomers"> <ul class="list-group"> <li ng-repeat="customer in allcustomers.data"><h4 class="list-group-item"> <strong>Customer {{$index}}</strong><br /> Id: {{customer.id}}<br /> First Name: {{customer.firstName}}<br /> Last Name: {{customer.lastName}} </h4></li> </ul> </div> <p>{{getResultMessage}}</p> </div> <div ng-controller="getcustomerController" class="col-md-3"> <h3>Customer by ID</h3> <input type="text" class="form-control" style="width: 100px;" ng-model="customerId" /> <br /> <button ng-click="getCustomer()">Get Customer</button> <div ng-show="showCustomer"> Id: {{customer.data.id}}<br /> First Name: {{customer.data.firstName}}<br /> Last Name: {{customer.data.lastName}} </div> <p>{{getResultMessage}}</p> </div> <div ng-controller="getcustomersbylastnameController" class="col-md-4"> <h3>Customers by LastName</h3> <input type="text" class="form-control" style="width: 100px;" ng-model="customerLastName" /><br /> <button ng-click="getCustomersByLastName()">Get Customers</button> <div ng-show="showCustomersByLastName"> <ul class="list-group"> <li ng-repeat="customer in allcustomersbylastname.data"><h4 class="list-group-item"> <strong>Customer {{$index}}</strong><br /> Id: {{customer.id}}<br /> First Name: {{customer.firstName}}<br /> Last Name: {{customer.lastName}} </h4></li> </ul> </div> <p>{{getResultMessage}}</p> </div> </div> </div> </body> </html> |
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/
– Fill Form to Post Customer Data & press Submit button.
Then press Get All Customers button, find Customer by Id, find Customers by Last Name:
– Open MySQL WorkBench to check database:
III. Source Code
Last updated on February 6, 2020.
great!
where is dialect and driver url information? and where are you reading application.properties?
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.