SlideShare a Scribd company logo
1 of 20
Consume Spring Data Rest
using AngularJS
Corneil du Plessis
corneil.duplessis@gmail.com
corneil@jumpco.io
@corneil
about.me/corneil
Introduction
What is Spring Data Rest
● Spring Data Repositories
● REST
Representational State Transfer
● HATEOAS
Hypermedia as Engine of Application State
Steps
● Spring Boot Application
– http://start.spring.io
– Entities
– Repositories
● Web Application
– Angular Service
– Angular Controller
– Web Page
Component Model
Spring Initializr
Entities
● JPA @Entity
● MongoDB @Document
@Entity
public class User {
@Id @GeneratedValue
private Long id;
@NotNull @Column(unique = true)
private String userId;
@Temporal(TemporalType.DATE)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private Date dateOfBirth;
@Email @NotNull
private String emailAddress;
@NotNull
private String fullName;
}
Repositories
public interface UserRepository extends CrudRepository<User, Long> {
User findOneByUserId(
@Param("userId") String userId);
List<User> findByUserIdContainsIgnoreCase(
@Param("input") String input);
}
Create Data
● SoapUI
● HAL Browser
Customizing Resources
● @RestResource
● @RepositoryRestResource
● Extend ResourceProcessor
● EntityLinks
● Projections
Custom Repository Behaviour
● Finder Methods
● Extend AbstractRepositoryEventListener
– onBefore and onAfter
– for Delete/Save/Create/Link
Angular Service
● $q Asyncronous service with deferred and promises
● $resourceProvider
● Module ngResource
● $resource service
● $cacheFactory
Angular Service
angular.module('springDataRestDemo')
.service('UserService',
['$q', '$resource', '$log', 'userCache', '$http',
function ($q, $resource, $log, userCache, $http) {
var Users = $resource('/rest/users', {}, {
create: {method: 'POST'},
list: {method: 'GET'}
});
return {
loadAllUsers: function () {
var deferred = $q.defer();
Users.list().$promise.then(
function (users) {
deferred.resolve(users._embedded.users);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
}
}
Angular Service
createUser: function (user) {
var deferred = $q.defer();
Users.create(user).$promise.then(
function (user) {
deferred.resolve(user);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
}
Angular Service
saveUser: function (user) {
var deferred = $q.defer();
var User = $resource(user._links.self.href, {}, {save: {method: 'PUT'}});
User.save(user).$promise.then(
function (data) {
deferred.resolve(data);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
}
Angular Controller
$scope.users = null;
$scope.promise = UserService.loadAllUsers();
$scope.promise.then(function (users) {
for (var i in users) {
users[i].selected = false;
}
$scope.users = users;
}, function (response) {
alert('Load error: ' + response.statusText);
});
Angular Controller
$scope.save = function () {
$scope.errorMessages = [];
$scope.user.dateOfBirth = moment($scope.dateOfBirth).format('YYYY-MM-DD');
var promise = $scope.newUser ? UserService.createUser($scope.user)
: UserService.saveUser($scope.user);
promise.then(
function (user) {
$mdDialog.hide(user);
NotificationService.toastMessage($scope.newUser ? 'User Created'
: 'User Saved');
},
function (response) {
if (response.status == 409 && response.statusText == 'Conflict') {
$scope.userForm.userId.$setValidity('unique', false);
} else {
var errorData = response.data;
$scope.errorMessages.push(errorData.message);
}
});
}
Web Page
<table ng-controller="UserController">
<thead>
<tr>
<th>User Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td ng-bind="user.userId"></td>
<td ng-bind="user.fullName"></td>
<td>
<button ng-click="editUser($event, user)" value="Edit"></button>
<button ng-click="deleteUser($event, user)" value="Delete"></button>
</td>
</tr>
</tbody>
</table>
Security
● Spring Data Rest
– @RepositoryRestResource(
exported = false)
– @RestResource(exported = false)
● Spring Security
– HttpSecurity
– @PreAuthorize(“hasRole('UserAdmin')”)
● Spring Data
– @Query(“select u from User u where u.name
== ?#{principal.name}”)
Questions
● Code - https://github.com/corneil/spring-data-rest-angular-demo
● Slides - http://www.slideshare.net/CorneilduPlessis
● Profile https://about.me/corneil
● Twitter @corneil

More Related Content

What's hot

10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rockmartincronje
 
Azure Mobile Services .NET Backend
Azure Mobile Services .NET BackendAzure Mobile Services .NET Backend
Azure Mobile Services .NET BackendShiju Varghese
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuerySiva Arunachalam
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB
 
IndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web AppsIndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web AppsAdégòkè Obasá
 
Azure doc db (slideshare)
Azure doc db (slideshare)Azure doc db (slideshare)
Azure doc db (slideshare)David Green
 
Cool NoSQL on Azure with DocumentDB
Cool NoSQL on Azure with DocumentDBCool NoSQL on Azure with DocumentDB
Cool NoSQL on Azure with DocumentDBJan Hentschel
 
When all you have is a hammer, everything looks like Javascript - ebookcraft ...
When all you have is a hammer, everything looks like Javascript - ebookcraft ...When all you have is a hammer, everything looks like Javascript - ebookcraft ...
When all you have is a hammer, everything looks like Javascript - ebookcraft ...BookNet Canada
 

What's hot (20)

Azure DocumentDB
Azure DocumentDBAzure DocumentDB
Azure DocumentDB
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
Java script
Java scriptJava script
Java script
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
Azure Mobile Services .NET Backend
Azure Mobile Services .NET BackendAzure Mobile Services .NET Backend
Azure Mobile Services .NET Backend
 
Simplify AJAX using jQuery
Simplify AJAX using jQuerySimplify AJAX using jQuery
Simplify AJAX using jQuery
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
Beyond the page
Beyond the pageBeyond the page
Beyond the page
 
Java script
Java scriptJava script
Java script
 
Web&java. jsp
Web&java. jspWeb&java. jsp
Web&java. jsp
 
J Query
J QueryJ Query
J Query
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
IndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web AppsIndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web Apps
 
Java script objects
Java script objectsJava script objects
Java script objects
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introduction
 
Azure doc db (slideshare)
Azure doc db (slideshare)Azure doc db (slideshare)
Azure doc db (slideshare)
 
HTML5
HTML5HTML5
HTML5
 
Cool NoSQL on Azure with DocumentDB
Cool NoSQL on Azure with DocumentDBCool NoSQL on Azure with DocumentDB
Cool NoSQL on Azure with DocumentDB
 
Azure DocumentDB
Azure DocumentDBAzure DocumentDB
Azure DocumentDB
 
When all you have is a hammer, everything looks like Javascript - ebookcraft ...
When all you have is a hammer, everything looks like Javascript - ebookcraft ...When all you have is a hammer, everything looks like Javascript - ebookcraft ...
When all you have is a hammer, everything looks like Javascript - ebookcraft ...
 

Similar to Consume Spring Data Rest with Angularjs

Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto UniversitySC5.io
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverSpike Brehm
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolboxShem Magnezi
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeVMware Tanzu
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND Enrique Oriol Bermúdez
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKitTaras Kalapun
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT TalkConstantine Mars
 
Architecture Components
Architecture Components Architecture Components
Architecture Components DataArt
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)Chris Clarke
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
A resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleA resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleAkihito Koriyama
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 

Similar to Consume Spring Data Rest with Angularjs (20)

Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolbox
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
The Past Year in Spring for Apache Geode
The Past Year in Spring for Apache GeodeThe Past Year in Spring for Apache Geode
The Past Year in Spring for Apache Geode
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND How to build an AngularJS backend-ready app WITHOUT BACKEND
How to build an AngularJS backend-ready app WITHOUT BACKEND
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Angularjs & REST
Angularjs & RESTAngularjs & REST
Angularjs & REST
 
RESTfull with RestKit
RESTfull with RestKitRESTfull with RestKit
RESTfull with RestKit
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)MEAN - Notes from the field (Full-Stack Development with Javascript)
MEAN - Notes from the field (Full-Stack Development with Javascript)
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
A resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangleA resource oriented framework using the DI/AOP/REST triangle
A resource oriented framework using the DI/AOP/REST triangle
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 

More from Corneil du Plessis

Sweet Streams (Are made of this)
Sweet Streams (Are made of this)Sweet Streams (Are made of this)
Sweet Streams (Are made of this)Corneil du Plessis
 
Cloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A WorkshopCloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A WorkshopCorneil du Plessis
 
Enhancements in Java 9 Streams
Enhancements in Java 9 StreamsEnhancements in Java 9 Streams
Enhancements in Java 9 StreamsCorneil du Plessis
 
Performance Comparison JVM Languages
Performance Comparison JVM LanguagesPerformance Comparison JVM Languages
Performance Comparison JVM LanguagesCorneil du Plessis
 
Microservices Patterns and Anti-Patterns
Microservices Patterns and Anti-PatternsMicroservices Patterns and Anti-Patterns
Microservices Patterns and Anti-PatternsCorneil du Plessis
 
Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Corneil du Plessis
 
Polyglot persistence with Spring Data
Polyglot persistence with Spring DataPolyglot persistence with Spring Data
Polyglot persistence with Spring DataCorneil du Plessis
 
Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forCorneil du Plessis
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10minCorneil du Plessis
 

More from Corneil du Plessis (15)

Sweet Streams (Are made of this)
Sweet Streams (Are made of this)Sweet Streams (Are made of this)
Sweet Streams (Are made of this)
 
Cloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A WorkshopCloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
Cloud Native Applications for Cloud Foundry using Spring Cloud : A Workshop
 
QueryDSL - Lightning Talk
QueryDSL - Lightning TalkQueryDSL - Lightning Talk
QueryDSL - Lightning Talk
 
Enhancements in Java 9 Streams
Enhancements in Java 9 StreamsEnhancements in Java 9 Streams
Enhancements in Java 9 Streams
 
Reactive Spring 5
Reactive Spring 5Reactive Spring 5
Reactive Spring 5
 
Empathic API-Design
Empathic API-DesignEmpathic API-Design
Empathic API-Design
 
Performance Comparison JVM Languages
Performance Comparison JVM LanguagesPerformance Comparison JVM Languages
Performance Comparison JVM Languages
 
Microservices Patterns and Anti-Patterns
Microservices Patterns and Anti-PatternsMicroservices Patterns and Anti-Patterns
Microservices Patterns and Anti-Patterns
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
 
Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!Gradle: The Build System you have been waiting for!
Gradle: The Build System you have been waiting for!
 
Polyglot persistence with Spring Data
Polyglot persistence with Spring DataPolyglot persistence with Spring Data
Polyglot persistence with Spring Data
 
Data repositories
Data repositoriesData repositories
Data repositories
 
Gradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting forGradle: The Build system you have been waiting for
Gradle: The Build system you have been waiting for
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
 
Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 

Recently uploaded

Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 

Recently uploaded (20)

Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 

Consume Spring Data Rest with Angularjs

  • 1. Consume Spring Data Rest using AngularJS Corneil du Plessis corneil.duplessis@gmail.com corneil@jumpco.io @corneil about.me/corneil
  • 3. What is Spring Data Rest ● Spring Data Repositories ● REST Representational State Transfer ● HATEOAS Hypermedia as Engine of Application State
  • 4. Steps ● Spring Boot Application – http://start.spring.io – Entities – Repositories ● Web Application – Angular Service – Angular Controller – Web Page
  • 7. Entities ● JPA @Entity ● MongoDB @Document @Entity public class User { @Id @GeneratedValue private Long id; @NotNull @Column(unique = true) private String userId; @Temporal(TemporalType.DATE) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private Date dateOfBirth; @Email @NotNull private String emailAddress; @NotNull private String fullName; }
  • 8. Repositories public interface UserRepository extends CrudRepository<User, Long> { User findOneByUserId( @Param("userId") String userId); List<User> findByUserIdContainsIgnoreCase( @Param("input") String input); }
  • 10. Customizing Resources ● @RestResource ● @RepositoryRestResource ● Extend ResourceProcessor ● EntityLinks ● Projections
  • 11. Custom Repository Behaviour ● Finder Methods ● Extend AbstractRepositoryEventListener – onBefore and onAfter – for Delete/Save/Create/Link
  • 12. Angular Service ● $q Asyncronous service with deferred and promises ● $resourceProvider ● Module ngResource ● $resource service ● $cacheFactory
  • 13. Angular Service angular.module('springDataRestDemo') .service('UserService', ['$q', '$resource', '$log', 'userCache', '$http', function ($q, $resource, $log, userCache, $http) { var Users = $resource('/rest/users', {}, { create: {method: 'POST'}, list: {method: 'GET'} }); return { loadAllUsers: function () { var deferred = $q.defer(); Users.list().$promise.then( function (users) { deferred.resolve(users._embedded.users); }, function (response) { deferred.reject(response); }); return deferred.promise; } }
  • 14. Angular Service createUser: function (user) { var deferred = $q.defer(); Users.create(user).$promise.then( function (user) { deferred.resolve(user); }, function (response) { deferred.reject(response); }); return deferred.promise; }
  • 15. Angular Service saveUser: function (user) { var deferred = $q.defer(); var User = $resource(user._links.self.href, {}, {save: {method: 'PUT'}}); User.save(user).$promise.then( function (data) { deferred.resolve(data); }, function (response) { deferred.reject(response); }); return deferred.promise; }
  • 16. Angular Controller $scope.users = null; $scope.promise = UserService.loadAllUsers(); $scope.promise.then(function (users) { for (var i in users) { users[i].selected = false; } $scope.users = users; }, function (response) { alert('Load error: ' + response.statusText); });
  • 17. Angular Controller $scope.save = function () { $scope.errorMessages = []; $scope.user.dateOfBirth = moment($scope.dateOfBirth).format('YYYY-MM-DD'); var promise = $scope.newUser ? UserService.createUser($scope.user) : UserService.saveUser($scope.user); promise.then( function (user) { $mdDialog.hide(user); NotificationService.toastMessage($scope.newUser ? 'User Created' : 'User Saved'); }, function (response) { if (response.status == 409 && response.statusText == 'Conflict') { $scope.userForm.userId.$setValidity('unique', false); } else { var errorData = response.data; $scope.errorMessages.push(errorData.message); } }); }
  • 18. Web Page <table ng-controller="UserController"> <thead> <tr> <th>User Id</th> <th>Name</th> <th>Action</th> </tr> </thead> <tbody> <tr ng-repeat="user in users"> <td ng-bind="user.userId"></td> <td ng-bind="user.fullName"></td> <td> <button ng-click="editUser($event, user)" value="Edit"></button> <button ng-click="deleteUser($event, user)" value="Delete"></button> </td> </tr> </tbody> </table>
  • 19. Security ● Spring Data Rest – @RepositoryRestResource( exported = false) – @RestResource(exported = false) ● Spring Security – HttpSecurity – @PreAuthorize(“hasRole('UserAdmin')”) ● Spring Data – @Query(“select u from User u where u.name == ?#{principal.name}”)
  • 20. Questions ● Code - https://github.com/corneil/spring-data-rest-angular-demo ● Slides - http://www.slideshare.net/CorneilduPlessis ● Profile https://about.me/corneil ● Twitter @corneil