Web Programming TutorialsHow To Build Application Using Angular JS & Spring Data JPA?

How To Build Application Using Angular JS & Spring Data JPA?

You can build an efficient web-based application with the Angular JS & Spring Data JPA. Each component has a distinct role to play. While the AngularJS acts as the rich client, helping to build efficient and dynamic Single Page Applications (SPA) which reduces load on servers and offers smarter page refreshes, the Spring Data JPA allows to set up a smart database layer that allows the client to quickly and accurately receive the data it requested.

What is Angular JS?

  • The AngularJS is an open-source and JavaScript-based framework for building dynamic web applications. AngularJS is provided and maintained by Google. AngularJS significantly reduces the effort needed in developing Single Page Applications (SPA). It provides a framework which reduces developer effort to write code. The main features of AngularJS are:
  • The Model-View-Controller (MVC) framework allows you to split the business logic layer, the data layer, and presentation layer into separate sections so that you could work on each section individually. The layers are loosely coupled with each other.
  • No significant data binding effort required. You do not need to write special code to bind the data to HTML, AngularJS does it for you.
  • Since the AngularJS is a framework, it provides a lot of preconfigured resources that you can use. To perform DOM manipulation, you would earlier need to write a lot of JavaScript code. But with AngularJS, you do not need to do so because it provides the snippets.

What is Spring Data JPA?

  • All enterprise applications need to interact with database to store and retrieve data. However, interacting with database has never been smooth because:Too much boilerplate code needs to be written to execute simple queries and perform pagination which is a waste of resources.
  • Software developers use proprietary framework to interact with the data bases which is not a seamless transaction.
  • Relational object models with reference to databases offer data access challenges to developers.The Spring Data JPA can solve the database access and data retrieval problem by providing a data access layer. From the developer’s perspective, all that needs to be done is to write the repository interfaces, including custom finder methods and the rest is done by Spring Data JPA. The main features of Spring Data JPA are: support for building Spring and JPA-based repositories; transparent auditing of domain class; support for pagination, dynamic query execution and can integrate custom data access code.

Reasons to build an application with Angular JS & Spring Data JPA

The main reasons a combination of AngularJS and Spring Data JPA should be preferred are mentioned below.

  • From the perspective of user experience, a seamless front-end or client and a server is necessary. The server should be able to smoothly access the database, send queries and retrieve the desired responses in a recognizable format. The faster the process is completed, the better it is for the user experience. Spring Data JPA enables the server to have a quick and smooth transaction.
  • Since the AngularJS is a framework in which, all logical units can be separated, it can interact well with the database layer set up with the help of the Spring Data JPOA, thereby paving the way for a smooth query and response system.

Approach

Typically, the following approach should be taken when building an application with AngularJS and Spring Data JPA.

  • Define the project structure first. In the structure, you must define all the folders, subfolders, dependencies and resources, whichever applicable in the context of the project.
  • Define the dependency management parameters or configuration in the POM.xml file. In most of the cases, the maven project POM will usually inherit from the spring-boot-starter-parent project.
  • Define the Spring Boot main class. Spring Boot offers the SpringApplication class to bootstrap a Spring application that will be started from the main() method.
    JPA configuration. In this step, you will be setting up the following repositories: Spring
  • Data @EnableJpaRepositories; Spring Boot DataSourceProperties; and Spring Boot DataSourceBuilder.

Pitfalls and limitations

The combination of AngularJS and Spring Data JPA is great for server and database interactivity but only if certain challenges are managed well. However, the AngularJS is an MVC framework and all its logical units — business logic layer, the data layer, and presentation layer – can be separated into distinct logical sections. Though this gives a lot of flexibility, it may also create compatibility issues with the database layer created with Spring Data JPA. For example, the presentation layer may not work, if changed or replaced with the database layer. So, it is imperative that whenever there are any changes in the AngularJS MVC framework, the compatibility with the database layer is kept in mind.

Building the application (Code)

In this section, we will try to build a sample application having AngularJS, Spring and JPA integration. It will be a Spring boot application.
First, we will check the pom.xml file. In this file, we will have dependencies for Spring boot, MySQL, Tomcat server.

[code]
<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>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-tomcat</artifactId>
	<scope>provided</scope>
</dependency> 
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
[/code]

Now, we will check the data model class. This is the model class mapped with the table in the database. Table column names will be mapped with the model entities by using annotations. The model class should be implementing Serializable interface.

Listing 2: Employee model class

[code]
package com.eduonix.spring.examples 
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 = "employee")
public class Employee implements Serializable { 
	private static final long serialVersionUID = -3008976332242234306L;
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id; 
	@Column(name = "firstname")
	private String firstName; 
	@Column(name = "lastname")
	private String lastName;
	
	public Employee(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}  
	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;
	}  
	@Override
	public String toString() {
		return String.format("Employee[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
	}
}
[/code]

Now, we will make one more model class, which is for response message. Purpose of this model class is to hold the response data.

Listing 3: Response data model class

[code]
package com.eduonix.spring.examples
public class ResponseData {
	private String status;
	private Object data; 
	public ResponseData() {
 
	} 
	public ResponseData(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;
	}
}
[/code]

After creating the model classes, we will be creating a repository class.

Listing 4: Sample repository class

[code]
package com.eduonix.spring.examples
 
import java.util.List; 
import org.springframework.data.repository.CrudRepository; 
import com.eduonix.spring.examples.Employee; 
public interface EmployeeRepository extends CrudRepository<Customer, Long> {
	Iterable<Customer> findAll();
}
[/code]

Now, we will be creating one sample controller class as shown below. Here we will check saving and retrieval part of Employee data.

Listing 5: Sample controller class

[code]
package com.eduonix.spring.examples
 
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.eduonix.spring.examples.ResponseData;
import com.eduonix.spring.examples.Employee;
import com.eduonix.spring.examples.EmployeeRepository;
 
@RestController
public class EmployeeController { 
	@Autowired
	EmployeeRepository repository; 
	@RequestMapping(value = "/postemployee", method = RequestMethod.POST)
	public void postEmployee(@RequestBody Employee employee) {
 
		repository.save(new Employee(employee.getFirstName(), employee.getLastName()));
	} 
	@RequestMapping("/findall")
	public Response findAll() {
 
		Iterable<Employee> employees = repository.findAll();
 
		return new Response("Done", employees);
	}
 
}
[/code]

After creating the controller part, we will be looking at the UI part of the application. Here we will create one JSP page with AngularJS tags to save and get Employee data.

Listing 6: Sample JSP page with Angular JS tags

[code]
<%@ 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 and JPA 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 - DB</h1> 
		<div class="row">
			<div ng-controller="postController" class="col-md-3">
				<form name="employeeForm" 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="getallemployeesController" class="col-md-3">
				<h3>All Employees</h3> 
<button ng-click="getAllEmployees()">Get All Employees</button> 
				<div ng-show="showAllEmployees">
					<ul class="list-group">
<li ng-repeat="employees in allemployees.data"><h4 class="list-group-item">
<strong>Employee {{$index}}</strong><br />
						Emp Id: {{employee.id}}<br />
									Emp First Name: {{employee.firstName}}<br />
Emp Last Name: {{employee.lastName}}
						</h4></li>
					</ul>
				</div>
				<p>{{getResultMessage}}</p>
			</div> 
		</div>
	</div>
</body>
</html>
[/code]

This is the JSP page for submitting employee data and retrieve all employees’ data.

Conclusion

The AngularJS and Spring Data JPA offers a great opportunity to build a robust and dynamic web application if the compatibility between the client layers and the database layer is managed intelligently. Spring data JPA is easy to implement and use. So, the developers will be able to use it easily and persist their data in the database.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -