Home  >  Spring 4

Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example

By Arvind Rai, May 05, 2016 | Modified on March 27, 2017
This page will walk through spring MVC 4 REST, AngularJS and hibernate 4 integration CRUD tutorial with ngResource example. ngResource is a AngularJS module which is used to interact with RESTful web services. We can use core AngularJS $http service also to interact with RESTful web services. The advantage of ngResource is that it provides higher level of abstraction. ngResource has $resource service which provides default methods like get, save, query, remove and delete to interact with RESTful web services. We can also create our custom methods associated with a HTTP request method. Here on this page we will provide complete example with create, read, update and delete (CRUD) operation using AngularJS ngResource and spring MVC RESTful web services. For update operation we will add a method in $resource service class associated with HTTP PUT request method. Now find the complete example step by step.

Software Used

Find the software used in our demo.
1. Java 8
2. Spring 4.2.5.RELEASE
3. Tomcat 8
4. Gradle
5. AngularJS 1.4.9
6. Hibernate 4
7. MySQL 5
8. Eclipse

Project Structure in Eclipse

Find the project structure in eclipse.
Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example

Spring, AngularJS and Hibernate Libraries

Find the gradle file to resolve spring and hibernate JAR dependencies.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'spring4'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web:1.3.3.RELEASE'
    compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.3.3.RELEASE'
    compile 'org.hibernate:hibernate-core:4.3.6.Final'
    compile 'mysql:mysql-connector-java:5.1.31'
    compile 'commons-dbcp:commons-dbcp:1.4'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:1.3.3.RELEASE'    
}  
In case we want to use maven, find pom.xml file.
pom.xml
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.concretepage</groupId>
	<artifactId>spring4</artifactId>
	<version>1</version>
	<packaging>war</packaging>
	<name>Spring</name>
	<description>Spring Demo Project</description>
	<parent>
	    <groupId>org.springframework.boot</groupId>
  	    <artifactId>spring-boot-starter-parent</artifactId>
	    <version>1.5.1.RELEASE</version>
 	    <relativePath/>
	</parent>
	<properties>
	    <java.version>1.8</java.version>
	</properties>
	<dependencies>
	  <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	  </dependency>
	  <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	  </dependency>
	  <dependency>
		 <groupId>org.hibernate</groupId>
		 <artifactId>hibernate-core</artifactId>
		 <version>4.3.6.Final</version>
	  </dependency>	  
	  <dependency>
		 <groupId>mysql</groupId>
		 <artifactId>mysql-connector-java</artifactId>
		 <version>5.1.31</version>
	  </dependency>	  	  	  
	  <dependency>
		 <groupId>commons-dbcp</groupId>
		 <artifactId>commons-dbcp</artifactId>
		 <version>1.4</version>
	  </dependency>    	  	  	  
	  <dependency>
		 <groupId>org.springframework.boot</groupId>
		 <artifactId>spring-boot-starter-tomcat</artifactId>
		 <scope>provided</scope>
	  </dependency>      
	</dependencies>
	<build>
	  <plugins>
	    <plugin>
		  <groupId>org.apache.maven.plugins</groupId>
		  <artifactId>maven-war-plugin</artifactId>
	    </plugin>
	  </plugins>
	</build>
</project>   
For AngularJS ngResource demo we need following libraries.
1. angular.min.js
2. angular-resource.min.js
To get the above JS libraries we are using npm. Install Node.js and using command prompt download JS libraries by running command as follows.

> npm install angular@1.4.9
> npm install angular-resource@1.4.9

Where 1.4.9 is library version, we can change version according to our requirement. We can download these libraries directly from URL too. The URLs are as follows.
URL for angular.min.js
https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js
URL for angular-resource.min.js
https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-resource.min.js

AngularJS ngResource

AngularJS ngResource module is used to interact with RESTful web services. ngResource module has $resource service. $resource service is a factory that creates resource object to interact with RESTful web services. Find the code to load ngResource module.
angular.module('myApp', ['ngResource']);
 
Now find the syntax to use $resource service.
$resource(url, [paramDefaults], [actions], options); 
 
It returns resource class object which has default methods to interact with RESTful web services. Those default methods are as follows.
{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} }; 
We can also add our custom methods. Suppose we want to add a custom method updatePerson with PUT http method. Then we need to do as follows.
app.factory('Person', ['$resource', function ($resource) {
    return $resource('http://localhost:8080/spring4-1/info/person/:personId', {personId: '@pid'},
	{
		updatePerson: {method: 'PUT'}
	}
    );
}]); 
Where pid is a field in our Person class. personId is a AngularJS variable which will assign its value to pid only when personId is not null. Suppose if personId has value 15, then the URL will be created as
http://localhost:8080/spring4-1/info/person/15
And if personId has no value, then it will be stripped and URL will be as follows.
http://localhost:8080/spring4-1/info/person
Now finally the resource has below set of methods.
{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'},
  'updatePerson': {method:'PUT'} }; 

Create View using AngularJS

Find the view which is being used to create, read, update and delete person.
home.jsp
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" /> 
    <title> Spring MVC 4 REST + AngularJS </title>
  </head>
  <body ng-app="myApp">
   <div ng-controller="PersonController as personCtrl">
       <h1> Spring MVC 4 REST + AngularJS </h1>
	<form name="personForm" method="POST">
	    <table>
		<tr><td colspan="2">
		  <div ng-if="personCtrl.flag != 'edit'">
		     <h3> Add New Person </h3> 
		  </div>
		  <div ng-if="personCtrl.flag == 'edit'">
		     <h3> Update Person for ID: {{ personCtrl.person.pid }} </h3> 
		  </div> </td>
		</tr>
		<tr>
		      <td>Name: </td> <td><input type="text" name="name" ng-model="personCtrl.person.name" required/> 
         	      <span ng-show="personForm.name.$error.required" class="msg-val">Name is required.</span> </td>
		</tr>
		<tr>
		      <td>Location: </td> <td> <input type="text" name="location" ng-model="personCtrl.person.location" required/> 
	              <span ng-show="personForm.location.$error.required" class="msg-val">Location is required.</span> </td>
		</tr>
		<tr>
		     <td colspan="2"> <span ng-if="personCtrl.flag=='created'" class="msg-success">Person successfully added.</span>
		     <span ng-if="personCtrl.flag=='failed'" class="msg-val">Person already exists.</span> </td>
		</tr>
	        <tr><td colspan="2">
	            <div ng-if="personCtrl.flag != 'edit'">
		       <input  type="submit" ng-click="personCtrl.addPerson()" value="Add Person"/> 
		       <input type="button" ng-click="personCtrl.reset()" value="Reset"/>
		    </div>
		    <div ng-if="personCtrl.flag == 'edit'">
		       <input  type="submit" ng-click="personCtrl.updatePersonDetail()" value="Update Person"/> 	
			   <input type="button" ng-click="personCtrl.cancelUpdate()" value="Cancel"/>				   
		    </div> </td>
		</tr>
		<tr>
		     <td colspan="2"> <span ng-if="personCtrl.flag=='deleted'" class="msg-success">Person successfully deleted.</span>
		</tr>
	    </table>     
	</form>
        <table>
	      <tr><th>ID </th> <th>Name</th> <th>Location</th></tr>
	      <tr ng-repeat="row in personCtrl.persons">
	         <td><span ng-bind="row.pid"></span></td>
	         <td><span ng-bind="row.name"></span></td>
	         <td><span ng-bind="row.location"></span></td>
	         <td>
		    <input type="button" ng-click="personCtrl.deletePerson(row.pid)" value="Delete"/>
		    <input type="button" ng-click="personCtrl.editPerson(row.pid)" value="Edit"/>
		    <span ng-if="personCtrl.flag=='updated' && row.pid==personCtrl.updatedId" class="msg-success">Person successfully updated.</span> </td> 
	      </tr>	
	</table>
	</div>
        <script src="${pageContext.request.contextPath}/app-resources/js/lib/angular.min.js"></script>
        <script src="${pageContext.request.contextPath}/app-resources/js/lib/angular-resource.min.js"></script>
	<script src="${pageContext.request.contextPath}/app-resources/js/app.js"></script>
	<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/app-resources/css/style.css"/>
 </body>
</html>   
Find AngularJS directives which are being used in our example.
ng-app : This directive is used to auto bootstrap AngularJS application.
ng-controller : It attaches a controller class to the view.
ng-if: It recreates or removes a portion of DOM tree on the basis of true and false of the expression.
ng-model: It bind input, select, textarea values to a property.
ng-show: It shows or hides the HTML element.
ng-click : It performs specified behavior on click of element.
ng-repeat : It runs a loop and instantiate a template for each item in a collection.
ng-bind : It replaces the text value of element with given expression.

In HTML 5, we can append data- prefix to the above directives as data-ng-app, data-ng-controller, data-ng-if etc. It avoids HTML validation errors.

Now find the CCS file used in our example.
style.css
.msg-val {
	color: red;
}
.msg-success {
	color: green;
} 

AngularJS ngResource CRUD Operation

We are creating AngularJS ngResource CRUD operation here. We will perform create, read, update and delete operation on person table using ngResource. Find the JS file.
app.js
var app = angular.module('myApp', ['ngResource']);
app.factory('Person', ['$resource', function ($resource) {
    return $resource('http://localhost:8080/spring4-1/info/person/:personId', {personId: '@pid'},
	{
		updatePerson: {method: 'PUT'}
	}
    );
}]);
app.controller('PersonController', ['$scope', 'Person', function($scope, Person) {
    var ob = this;
    ob.persons=[];
    ob.person = new Person(); 
    ob.fetchAllPersons = function(){
        ob.persons = Person.query();
    };
    ob.fetchAllPersons();
    ob.addPerson = function(){
	console.log('Inside save');
	if($scope.personForm.$valid) {
	  ob.person.$save(function(person){
	     console.log(person); 
	     ob.flag= 'created';	
	     ob.reset();	
	     ob.fetchAllPersons();
	  },
	  function(err){
	     console.log(err.status);
	     ob.flag='failed';
	  }
          );
        }
    }; 
    ob.editPerson = function(id){
	    console.log('Inside edit');
            ob.person = Person.get({ personId: id}, function() {
	       ob.flag = 'edit'; 
	    });
    };    
    ob.updatePersonDetail = function(){
	console.log('Inside update');
	if($scope.personForm.$valid) {
    	   ob.person.$updatePerson(function(person){
    		console.log(person); 
		ob.updatedId = person.pid;
		ob.reset();
		ob.flag = 'updated'; 
    		ob.fetchAllPersons();
           });
	}
    };	
    ob.deletePerson = function(id){
	    console.log('Inside delete');
	    ob.person = Person.delete({ personId: id}, function() {
		ob.reset();  
		ob.flag = 'deleted';
    		ob.fetchAllPersons(); 
	    });
    };		
    ob.reset = function(){
    	ob.person = new Person();
        $scope.personForm.$setPristine();
    };	
    ob.cancelUpdate = function(id){
	    ob.person = new Person();
	    ob.flag= '';	
   	    ob.fetchAllPersons();
    };    
}]);     
Now we will discuss here CRUD methods.
1. Add Person:

To add a person we have created below AngularJS method.
ob.addPerson = function(){
 console.log('Inside save');
 if($scope.personForm.$valid) {
    ob.person.$save(function(person){
	 console.log(person); 
	 ob.flag= 'created';	
	 ob.reset();	
	 ob.fetchAllPersons();
	},
	function(err){
	 console.log(err.status);
	 ob.flag='failed';
	}
    );
  }
}; 
To save the person we are using $save() method which will use HTTP POST request method. To call $save() on AngularJS person object, first we are checking if HTML form has been validated or not. AngularJS will use the below URL to post the form with POST method.
http://localhost:8080/spring4-1/info/person
In Spring MVC, the below method will be mapped.
@RequestMapping(value= "/person", method = RequestMethod.POST)
public ResponseEntity<Void> addPerson(@RequestBody Person person, UriComponentsBuilder builder) {
	boolean flag = personService.addPerson(person);
	if (flag == false) {
		return new ResponseEntity<Void>(HttpStatus.CONFLICT);
	}
	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(builder.path("/person/{id}").buildAndExpand(person.getPid()).toUri());
	return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
} 
Here we need to send http status as HttpStatus.CREATED if person successfully added. We need to send URL for newly added person in header location. If person already exits, we send HttpStatus.CONFLICT status.
2. Fetch Person:

To fetch all persons, we have created AngularJS method as follows.
ob.persons=[];
ob.fetchAllPersons = function(){
	ob.persons = Person.query();
}; 
It will use URL as
http://localhost:8080/spring4-1/info/person
The HTTP request method will be GET. It will return JSON array. In spring controller, the below method will be mapped.
@RequestMapping(value= "/person", method = RequestMethod.GET)
public ResponseEntity<List<Person>> getAllPersons() {
	List<Person> list = personService.getAllPersons();
	return new ResponseEntity<List<Person>>(list, HttpStatus.OK);
} 
If we want to fetch a single person for the given person id, we need to call AngularJS ngResource get method.
ob.person = Person.get({ personId: id}, function() {
   ob.flag = 'edit'; 
}); 
Suppose personId is 15, then the URL will be as follows.
http://localhost:8080/spring4-1/info/person/15
It will use GET request method. In spring controller, the above URL will map the below method.
@RequestMapping(value="/person/{id}", method = RequestMethod.GET )
public ResponseEntity<Person> getPersonById(@PathVariable("id") Integer id) {
	Person person = personService.getPersonById(id);
	return new ResponseEntity<Person>(person, HttpStatus.OK);
} 

3. Update Person:

To update a person, we have created a custom method as updatePerson with PUT request method in AngularJS resource class. We are using this method as following.
ob.updatePersonDetail = function(){
  console.log('Inside update');
  if($scope.personForm.$valid) {
    ob.person.$updatePerson(function(person){
	console.log(person); 
	ob.updatedId = person.pid;
	ob.reset();
	ob.flag = 'updated'; 
	ob.fetchAllPersons();
    });
  }
}; 
This will create the URL as given below.
http://localhost:8080/spring4-1/info/person
Here this URL will hit with PUT request method. Find the mapping method in spring controller.
@RequestMapping(value="/person/{id}", method = RequestMethod.PUT )
public ResponseEntity<Person> updatePerson(@RequestBody Person person) {
	personService.updatePerson(person);
	return new ResponseEntity<Person>(person, HttpStatus.OK);
} 

4. Delete Person:

To delete a person, we have created following AngularJS method.
ob.deletePerson = function(id){
	console.log('Inside delete');
	ob.person = Person.delete({ personId: id}, function() {
	   ob.reset();  
	   ob.flag = 'deleted';
	   ob.fetchAllPersons(); 
	});
};	 
Here we are using the default method delete of AngularJS resource class which uses DELETE request method. Suppose we are deleting a person with id 15, then it uses the URL as follows.
http://localhost:8080/spring4-1/info/person/15
Here it will use DELETE request method. In spring controller, it will map the following method.
@RequestMapping(value="/person/{id}", method = RequestMethod.DELETE )
public ResponseEntity<Void> deletePerson(@PathVariable("id") Integer id) {
	personService.deletePerson(id);
	return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
} 
After successful delete, we need to send HTTP status HttpStatus.NO_CONTENT.

Spring MVC REST with ResponseEntity and @Controller

Find the controller class for Spring MVC RESTful web services.
PersonController.java
package com.concretepage.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.util.UriComponentsBuilder;
import com.concretepage.entity.Person;
import com.concretepage.service.IPersonService;
@Controller
@RequestMapping("/info")
public class PersonController {
	@Autowired
	private IPersonService personService;
	@RequestMapping("/home")
	public String home() {
 		return "home";
 	}
	@RequestMapping(value="/person/{id}", method = RequestMethod.GET )
	public ResponseEntity<Person> getPersonById(@PathVariable("id") Integer id) {
		Person person = personService.getPersonById(id);
		return new ResponseEntity<Person>(person, HttpStatus.OK);
	}
	@RequestMapping(value= "/person", method = RequestMethod.GET)
	public ResponseEntity<List<Person>> getAllPersons() {
		List<Person> list = personService.getAllPersons();
		return new ResponseEntity<List<Person>>(list, HttpStatus.OK);
	}
	@RequestMapping(value= "/person", method = RequestMethod.POST)
	public ResponseEntity<Void> addPerson(@RequestBody Person person, UriComponentsBuilder builder) {
        boolean flag = personService.addPerson(person);
               if (flag == false) {
        	  return new ResponseEntity<Void>(HttpStatus.CONFLICT);
               }
               HttpHeaders headers = new HttpHeaders();
               headers.setLocation(builder.path("/person/{id}").buildAndExpand(person.getPid()).toUri());
               return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
	}
	@RequestMapping(value="/person/{id}", method = RequestMethod.PUT )
	public ResponseEntity<Person> updatePerson(@RequestBody Person person) {
		personService.updatePerson(person);
		return new ResponseEntity<Person>(person, HttpStatus.OK);
	}
	@RequestMapping(value="/person/{id}", method = RequestMethod.DELETE )
	public ResponseEntity<Void> deletePerson(@PathVariable("id") Integer id) {
		personService.deletePerson(id);
		return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
	}	
}   
Here we are using ResponseEntity with @Controller.
ResponseEntity : It extends HttpEntity to accommodate HttpStatus. HttpEntity contains headers and body. So finally ResponseEntity represents response with headers, body and HTTP status code.
UriComponentsBuilder : It is the builder for UriComponents which is the collection of URI components.

Difference: REST Controller using @ResponseStatus with @RestController Or ResponseEntity with @Controller

We can create our spring controller with @ResponseStatus and @RestController as given below.
@RestController
@RequestMapping("/info")
public class PersonController {
	@ResponseStatus(HttpStatus.OK)
	@RequestMapping(value= "/person", method = RequestMethod.GET)
	public List<Person> getAllPersons() {
		List<Person> list = personService.getAllPersons();
		return list;
	}
} 
In the above code, we are using @RestController. As we know that
@RestController = @Controller + @ResponseBody
@ResponseBody contains web resource body. While responding to AngularJS methods, we need to send HTTP status code and to send it, we annotate controller method with @ResponseStatus.
In case we are using ResponseEntity with @Controller, we will write code as follows.
@Controller
@RequestMapping("/info")
public class PersonController {
	@RequestMapping(value= "/person", method = RequestMethod.GET)
	public ResponseEntity<List<Person>> getAllPersons() {
		List<Person> list = personService.getAllPersons();
		return new ResponseEntity<List<Person>>(list, HttpStatus.OK);
	}
} 
Using ResponseEntity is better because to manage response body, headers and HTTP status is easy while responding to client. In our demo we have used ResponseEntity with @Controller annotation.

Create MySQL Table and Entity

Find the table used in our example with two dummy rows.
Table: person
CREATE DATABASE IF NOT EXISTS `concretepage` 
USE `concretepage`;

CREATE TABLE IF NOT EXISTS `person` (
  `pid` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `location` varchar(100) NOT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;

INSERT INTO `person` (`pid`, `name`, `location`) VALUES
	(1, 'Mahesh', 'Varanasi'),
	(2, 'Ram', 'Ayodhya'); 
Find the entity class.
Person.java
package com.concretepage.entity;
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="person")
public class Person implements Serializable { 
	private static final long serialVersionUID = 1L;
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="pid")
        private int pid;  
	@Column(name="name")
        private String name;
	@Column(name="location")	
	private String location;
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
}  

Create DAO with HibernateTemplate

Find DAO class with HibernateTemplate for CRUD operation.
IPersonDAO.java
package com.concretepage.dao;
import java.util.List;
import com.concretepage.entity.Person;
public interface IPersonDAO {
    List<Person> getAllPersons();
    Person getPersonById(int pid);
    void addPerson(Person person);
    void updatePerson(Person person);
    void deletePerson(int pid);
    boolean personExists(String name, String location);
} 
PersonDAO.java
package com.concretepage.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.concretepage.entity.Person;
@Transactional
@Repository
public class PersonDAO implements IPersonDAO {
	@Autowired
	private HibernateTemplate  hibernateTemplate;
	@Override
	public Person getPersonById(int pid) {
		return hibernateTemplate.get(Person.class, pid);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Person> getAllPersons() {
		String hql = "FROM Person as p ORDER BY p.pid";
		return (List<Person>) hibernateTemplate.find(hql);
	}	
	@Override
	public void addPerson(Person person) {
		hibernateTemplate.save(person);
	}
	@Override
	public void updatePerson(Person person) {
		Person p = getPersonById(person.getPid());
		p.setName(person.getName());
		p.setLocation(person.getLocation());
		hibernateTemplate.update(p);
	}
	@Override
	public void deletePerson(int pid) {
		hibernateTemplate.delete(getPersonById(pid));
	}
	@SuppressWarnings("unchecked")
	@Override
	public boolean personExists(String name, String location) {
		String hql = "FROM Person as p WHERE p.name = ? and p.location = ?";
		List<Person> persons = (List<Person>) hibernateTemplate.find(hql, name, location);
		return persons.size() > 0 ? true : false;
	}
} 

Create Service

Find our service interface and its implementation for CRUD operation.
IPersonService.java
package com.concretepage.service;
import java.util.List;
import com.concretepage.entity.Person;
public interface IPersonService {
     List<Person> getAllPersons();
     Person getPersonById(int pid);
     boolean addPerson(Person person);
     void updatePerson(Person person);
     void deletePerson(int pid);
}
PersonService.java
package com.concretepage.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.concretepage.dao.IPersonDAO;
import com.concretepage.entity.Person;
@Service
public class PersonService implements IPersonService {
	@Autowired
	private IPersonDAO personDAO;
	@Override
	public Person getPersonById(int pid) {
		Person obj = personDAO.getPersonById(pid);
		return obj;
	}	
	@Override
	public List<Person> getAllPersons(){
		return personDAO.getAllPersons();
	}
	@Override
	public synchronized boolean addPerson(Person person){
               if (personDAO.personExists(person.getName(), person.getLocation())) {
    	           return false;
               } else {
    	           personDAO.addPerson(person);
    	           return true;
               }
	}
	@Override
	public void updatePerson(Person person) {
		personDAO.updatePerson(person);
	}
	@Override
	public void deletePerson(int pid) {
		personDAO.deletePerson(pid);
	}
} 

Configuration and Web Application Initializer Class

Find configuration class and web application initializer class.
AppConfig.java
package com.concretepage.config;  
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration 
@ComponentScan("com.concretepage") 
@EnableWebMvc   
public class AppConfig extends WebMvcConfigurerAdapter  {  
    @Bean  
    public InternalResourceViewResolver viewResolver() {  
	InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
        resolver.setPrefix("/WEB-INF/view/");  
        resolver.setSuffix(".jsp");
        return resolver;  
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler("/app-resources/**").addResourceLocations("/resources/");
    }    
} 
DBConfig.java
package com.concretepage.config;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.concretepage.entity.Person;
@Configuration 
@EnableTransactionManagement
public class DBConfig {
	@Bean
	public HibernateTemplate hibernateTemplate() {
		return new HibernateTemplate(sessionFactory());
	}
	@Bean
	public SessionFactory sessionFactory() {
		return new LocalSessionFactoryBuilder(getDataSource())
		   .addAnnotatedClasses(Person.class)
		   .buildSessionFactory();
	}
	@Bean
	public DataSource getDataSource() {
	        BasicDataSource dataSource = new BasicDataSource();
	        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	        dataSource.setUrl("jdbc:mysql://localhost:3306/concretepage");
	        dataSource.setUsername("root");
	        dataSource.setPassword("");
	        return dataSource;
	}
	@Bean
	public HibernateTransactionManager hibTransMan(){
		return new HibernateTransactionManager(sessionFactory());
	}
} 
WebAppInitializer.java
package com.concretepage.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppConfig.class };
	}
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
} 

Run Application

To run the application, follow below steps.
1. Create database using MySQL.
2. Download source code.
3. Go to the project root directory through command prompt.
4. Run the gradle command as gradle clean build
5. Deploy war file in tomcat.
6. Access the URL http://localhost:8080/spring4-1/info/home

We will get below page.
Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example
To add new person, enter name and location and click on Add Person
Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example
To update a person, first click on Edit and then perform the changes.
Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example
Now click on Update Person, we will get our data updated.
Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example
To delete a person, click on Delete and person will be deleted.
Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example

Now find the browser console output.
Inside save 
Object { name: "Manik", location: "Bhopal", $resolved: true } 
Inside edit 
Inside update 
Object { pid: 3, location: "Patna", name: "Manik", $promise: Object, $resolved: true } 
Inside delete  


Find the link for Angular 2 Http CRUD operation with Spring Boot.

Spring Boot REST + Angular 2 + JPA + Hibernate + MySQL CRUD Example

Reference

AngularJS $resource

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS



Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us