SlideShare uma empresa Scribd logo
1 de 25
Polyglot persistence with Spring Data
Corneil du Plessis
corneil.duplessis@gmail.com
https://about.me/corneil
@corneil
Quotes
Everything should be made as simple as
possible, but not simpler.
Albert Einstein
Definitions
● Persistence
● the action or fact of persisting
● the quality or state of being persistent; especially :
perseverance
● the quality that allows someone to continue doing
something or trying to do something even though it is
difficult or opposed by other people
● the state of occurring or existing beyond the usual,
expected, or normal time
Definitions
● Polyglot
● knowing or using several languages
● computer program or script written in a valid form of
multiple programming languages
Polyglot – Sample
#define a /*
#<?php
echo "010Hello, world!n";// 2> /dev/null > /dev/null  ;
// 2> /dev/null; x=a;
$x=5; // 2> /dev/null  ;
if (($x))
// 2> /dev/null; then
return 0;
// 2> /dev/null; fi
#define e ?>
#define b */
#include <stdio.h>
#define main() int main(void)
#define printf printf(
#define true )
#define function
function main()
{
printf "Hello, world!n"true/* 2> /dev/null | grep -v true*/;
return 0;
}
#define c /*
main
#*/
What is going on in persistence?
● RDBMS doesn't scale to Internet (millions of users and billions of transactions).
● Ability to interact with multiple data stores depending on specific use cases
● MongoDB or Couchbase for Customer data
● RDBMS for financial transactions
● Elasticsearch, Solr, Cassandra or HBase for audit trails and analytics and
search
● Redis and Gemfire for shared state
● Neo4J, OrientDB for Graph Data
● RDF Stores for Semantic Reasoning
● Hadoop for Big Data
Simple JDBC Example
import java.sql.*;
public class SimpleDemoJDBC {
public Person getPerson(String userId, Connection conn) throws SQLException {
Person result = null;
PreparedStatement pstmt = conn.prepareStatement(
"SELECT userId, email, name FROM persons WHERE userId = ?");
pstmt.setString(1, userId);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
result = new Person(rs.getString(1), rs.getString(2), rs.getString(3));
}
rs.close();
pstmt.close();
return result;
}
public void updatePerson(Person person, Connection conn) throws SQLException {
Statement stmt = conn.prepareStatement(
"UPDATE persons SET email = ?, name = ? WHERE userId = ?");
stmt.setString(1, person.getEmail());
stmt.setString(2, person.getName());
stmt.setString(3, person.getUserId());
stmt.executeUpdate();
stmt.close();
}
}
SQLJ what happened there?
import java.sql.*;
public class SimpleDemoSQLJ {
public Person getPerson(String userId) throws SQLException {
Person person = new Person();
#sql { SELECT userId, email, name INTO
:person.userId, :person.email, :person.userId
FROM persons WHERE userId = :userId
};
return person;
}
public void updatePerson(Person person) throws SQLException {
#sql { UPDATE persons SET email = :person.email,
name = :person.name
WHERE userId = :person.userId
};
}
}
Syntax may be incorrect
MongoDB Sample
DB db = mongo.getDB("MyData");
DBCollection persons = db.getCollection("Persons");
public Person findPerson(String userId) {
Iterable<Document> documents = persons.find(
new Document("userId", userId));
for(Document doc : documents) {
return new Person(doc.get("userId", String.class),
doc.get("name", String.class),
doc.get("email", String.class));
}
return null;
}
public void updatePerson(Person person) {
Document doc = new Document(“userId”, person.getUserId());
doc.put(“email”, person.getEmail());
doc.put(“name”, person.getName());
Document query = new Document("userId", person.getUserId());
Document update = new Document(“$set”, doc);
persons.update(query, update);
}
What are we talking about?
● Improve programmer productivity.
● Polyglot persistence using one language.
● The language of Spring Data.
Spring for programmer productivity
● Spring does not provide ORM
● Spring does not provide Database
● Spring as inversion of control container
● Spring templates for JMS, JDBC, Hibernate, JPA,
MongoDB and much more.
Why Spring Data?
● Best practice indicates you should have Data Access
Components or a Data Service Layer.
● How often do you make simple mistakes interacting with
EntityManager?
● Different API for each store.
● It should be easier...
What is Spring Data?
● Spring Data is an open source project at
http://projects.spring.io/spring-data/ managed by Pivotal Software.
● Spring Data relies on Spring Framework.
● Spring Data provides a set of common patterns for persisting data
using existing libraries.
● Spring Data provides a Repository Interface
● Spring Data provides finder methods
● Spring Data provides support for QueryDSL
● Spring Data simplifies persistence
● Spring Data enables polyglot persistence
Spring Data sub projects
● Commons
● JPA
● JDBC Extensions
● MongoDB
● Neo4J
● Redis
● HBase
● Hadoop
● Solr
● GemFire
● REST provider
● Community Projects
● OrientDB
● RDF
● Couchbase
● Elasticsearch
● Cassandra
● DynamoDB
How Spring Data?
● Configure Spring Data for specific technology
● Define Entity as per relevant library or framework
● Declare Repository Interface
● Spring Data provides Repository Implementation
● Spring Framework injects Repository implementation
Spring Data Samples – Configuration
● EntityManagerFactory as normal for JPA
<jpa:repositories
base-package="com.springframework.data.demo" />
OR
@EnableJpaRepositories({"com.springframework.data.demo"})
Spring Data Sample – Entity
@Entity
public class User {
@Id
Long id;
String fullName;
String gender;
Date dateOfBirth;
}
Getters and Setters removed for brevity
Spring Data Sample – Repository
public interface UserRepository
extends CrudRepository<User, Long> {
}
● Crud Repository provides type-safe methods for save,
delete, load
Spring Data Sample - Injection
@Service
public class MyDataServiceImpl {
@AutoWired
protected UserRepository userRepo;
public void createUser(User user) {
userRepo.save(user);
}
}
Spring Data Sample – Finders
public interface UserRepository
extends CrudRepository<User, Long> {
List<User> findByGender(String genderCode);
List<User> findByDateOfBirthBetween(
Date startDate, Date endDate);
}
● Crud Repository provides query predicates based on method name like:
findByNameOrderByDateOfBirthDesc
findByNameAndGender
● Finder method tokens
● And, Or, Is, Equals, Between, LessThan, LessThanEqual, GreaterThan,
GreaterThanEqual, After, Before, IsNull, IsNotNull, NotNull, Like,
NotLike, StartingWith, EndingWith, Containing, Not, In, NotIn, True,
False, IgnoreCase
Spring Data Query
● Specific to technology
● Annotated finder method
@Query("select * from User u where u.gender = ?")
List<User> findUsersForGender(String code)
Getters and Setters removed for brevity
Spring Data Sample – QueryDSL
@Entity
@QueryEntity
public class User {
@Id
private Long id;
private String fullName;
private String gender;
private Date dateOfBirth;
}
● QueryDSL generates QUser for creating type-safe query.
class UserRepository extends
QueryDslPredicateExecutor<User>,
CrudRepository<User,Long> {
}
import static Quser.*;
List<User> users = userRepo.findAll(user.gender.eq('M'));
List<User> users = userRepo.findAll(user.fullName.like("%abc%"));
Spring Data – Paging and Sorting
class UserRepository extends
PagingAndSortingRepository<User, Long> {
}
...
Pageble page = new PageRequest(1,20);
Page<User> users = userRepo.findAll(user.gender.eq("M"), page);
● Create Pageable in UI and add to method.
● Add Pageble to finders
● Add Sort to finders
● Page<User> can be used to retrieve pages.
● Slice<User> can only retrieve next slice.
Spring Data – Notes
● Shared code for multiple technologies like MongoDB,
JPA, Neo4J etc.
● Entity Mapping is usually specific to technology.
● Common Repository methods can be implemented.
● Paging and Sorting support.
Spring Data – Demo and
Questions
● JPA With Hibernate
● MongoDB
● QueryDSL
● Demo code at
https://github.com/corneil/spring-data-demo

Mais conteúdo relacionado

Mais procurados

An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAndrei Sebastian Cîmpean
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JSHamdi Hmidi
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJSAll Things Open
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
Web components with java by Haijian Wang
Web components with java by Haijian WangWeb components with java by Haijian Wang
Web components with java by Haijian WangGWTcon
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Codemotion
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...DicodingEvent
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and ReduxGlib Kechyn
 
AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)Nitya Narasimhan
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10minszmcartor
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with ReduxFITC
 

Mais procurados (20)

An approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSocketsAn approach to responsive, realtime with Backbone.js and WebSockets
An approach to responsive, realtime with Backbone.js and WebSockets
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JS
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Indexed db
Indexed dbIndexed db
Indexed db
 
Web components with java by Haijian Wang
Web components with java by Haijian WangWeb components with java by Haijian Wang
Web components with java by Haijian Wang
 
ReactJS for Beginners
ReactJS for BeginnersReactJS for Beginners
ReactJS for Beginners
 
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
Building multi lingual and empatic bots - Sander van den Hoven - Codemotion A...
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and Redux
 
React, Flux and a little bit of Redux
React, Flux and a little bit of ReduxReact, Flux and a little bit of Redux
React, Flux and a little bit of Redux
 
AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)AngularJS Deep Dives (NYC GDG Apr 2013)
AngularJS Deep Dives (NYC GDG Apr 2013)
 
Create a Core Data Observer in 10mins
Create a Core Data Observer in 10minsCreate a Core Data Observer in 10mins
Create a Core Data Observer in 10mins
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 

Semelhante a Polyglot persistence with Spring Data

Five android architecture
Five android architectureFive android architecture
Five android architectureTomislav Homan
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
How to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinHow to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinSigma Software
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATIONkrutitrivedi
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaMongoDB
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRCtepsum
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core ModuleKatie Gulley
 

Semelhante a Polyglot persistence with Spring Data (20)

Spring Data in 10 minutes
Spring Data in 10 minutesSpring Data in 10 minutes
Spring Data in 10 minutes
 
Five android architecture
Five android architectureFive android architecture
Five android architecture
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
How to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita GalkinHow to make a high-quality Node.js app, Nikita Galkin
How to make a high-quality Node.js app, Nikita Galkin
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Spring.io
Spring.ioSpring.io
Spring.io
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Webinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and JavaWebinar: Building Your First App with MongoDB and Java
Webinar: Building Your First App with MongoDB and Java
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRC
 
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 

Mais de 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
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsCorneil 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
 
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
 

Mais de Corneil du Plessis (14)

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
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with Angularjs
 
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!
 
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
 

Último

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 

Último (20)

%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 

Polyglot persistence with Spring Data

  • 1. Polyglot persistence with Spring Data Corneil du Plessis corneil.duplessis@gmail.com https://about.me/corneil @corneil
  • 2. Quotes Everything should be made as simple as possible, but not simpler. Albert Einstein
  • 3. Definitions ● Persistence ● the action or fact of persisting ● the quality or state of being persistent; especially : perseverance ● the quality that allows someone to continue doing something or trying to do something even though it is difficult or opposed by other people ● the state of occurring or existing beyond the usual, expected, or normal time
  • 4. Definitions ● Polyglot ● knowing or using several languages ● computer program or script written in a valid form of multiple programming languages
  • 5. Polyglot – Sample #define a /* #<?php echo "010Hello, world!n";// 2> /dev/null > /dev/null ; // 2> /dev/null; x=a; $x=5; // 2> /dev/null ; if (($x)) // 2> /dev/null; then return 0; // 2> /dev/null; fi #define e ?> #define b */ #include <stdio.h> #define main() int main(void) #define printf printf( #define true ) #define function function main() { printf "Hello, world!n"true/* 2> /dev/null | grep -v true*/; return 0; } #define c /* main #*/
  • 6. What is going on in persistence? ● RDBMS doesn't scale to Internet (millions of users and billions of transactions). ● Ability to interact with multiple data stores depending on specific use cases ● MongoDB or Couchbase for Customer data ● RDBMS for financial transactions ● Elasticsearch, Solr, Cassandra or HBase for audit trails and analytics and search ● Redis and Gemfire for shared state ● Neo4J, OrientDB for Graph Data ● RDF Stores for Semantic Reasoning ● Hadoop for Big Data
  • 7. Simple JDBC Example import java.sql.*; public class SimpleDemoJDBC { public Person getPerson(String userId, Connection conn) throws SQLException { Person result = null; PreparedStatement pstmt = conn.prepareStatement( "SELECT userId, email, name FROM persons WHERE userId = ?"); pstmt.setString(1, userId); ResultSet rs = pstmt.executeQuery(); if(rs.next()) { result = new Person(rs.getString(1), rs.getString(2), rs.getString(3)); } rs.close(); pstmt.close(); return result; } public void updatePerson(Person person, Connection conn) throws SQLException { Statement stmt = conn.prepareStatement( "UPDATE persons SET email = ?, name = ? WHERE userId = ?"); stmt.setString(1, person.getEmail()); stmt.setString(2, person.getName()); stmt.setString(3, person.getUserId()); stmt.executeUpdate(); stmt.close(); } }
  • 8. SQLJ what happened there? import java.sql.*; public class SimpleDemoSQLJ { public Person getPerson(String userId) throws SQLException { Person person = new Person(); #sql { SELECT userId, email, name INTO :person.userId, :person.email, :person.userId FROM persons WHERE userId = :userId }; return person; } public void updatePerson(Person person) throws SQLException { #sql { UPDATE persons SET email = :person.email, name = :person.name WHERE userId = :person.userId }; } } Syntax may be incorrect
  • 9. MongoDB Sample DB db = mongo.getDB("MyData"); DBCollection persons = db.getCollection("Persons"); public Person findPerson(String userId) { Iterable<Document> documents = persons.find( new Document("userId", userId)); for(Document doc : documents) { return new Person(doc.get("userId", String.class), doc.get("name", String.class), doc.get("email", String.class)); } return null; } public void updatePerson(Person person) { Document doc = new Document(“userId”, person.getUserId()); doc.put(“email”, person.getEmail()); doc.put(“name”, person.getName()); Document query = new Document("userId", person.getUserId()); Document update = new Document(“$set”, doc); persons.update(query, update); }
  • 10. What are we talking about? ● Improve programmer productivity. ● Polyglot persistence using one language. ● The language of Spring Data.
  • 11. Spring for programmer productivity ● Spring does not provide ORM ● Spring does not provide Database ● Spring as inversion of control container ● Spring templates for JMS, JDBC, Hibernate, JPA, MongoDB and much more.
  • 12. Why Spring Data? ● Best practice indicates you should have Data Access Components or a Data Service Layer. ● How often do you make simple mistakes interacting with EntityManager? ● Different API for each store. ● It should be easier...
  • 13. What is Spring Data? ● Spring Data is an open source project at http://projects.spring.io/spring-data/ managed by Pivotal Software. ● Spring Data relies on Spring Framework. ● Spring Data provides a set of common patterns for persisting data using existing libraries. ● Spring Data provides a Repository Interface ● Spring Data provides finder methods ● Spring Data provides support for QueryDSL ● Spring Data simplifies persistence ● Spring Data enables polyglot persistence
  • 14. Spring Data sub projects ● Commons ● JPA ● JDBC Extensions ● MongoDB ● Neo4J ● Redis ● HBase ● Hadoop ● Solr ● GemFire ● REST provider ● Community Projects ● OrientDB ● RDF ● Couchbase ● Elasticsearch ● Cassandra ● DynamoDB
  • 15. How Spring Data? ● Configure Spring Data for specific technology ● Define Entity as per relevant library or framework ● Declare Repository Interface ● Spring Data provides Repository Implementation ● Spring Framework injects Repository implementation
  • 16. Spring Data Samples – Configuration ● EntityManagerFactory as normal for JPA <jpa:repositories base-package="com.springframework.data.demo" /> OR @EnableJpaRepositories({"com.springframework.data.demo"})
  • 17. Spring Data Sample – Entity @Entity public class User { @Id Long id; String fullName; String gender; Date dateOfBirth; } Getters and Setters removed for brevity
  • 18. Spring Data Sample – Repository public interface UserRepository extends CrudRepository<User, Long> { } ● Crud Repository provides type-safe methods for save, delete, load
  • 19. Spring Data Sample - Injection @Service public class MyDataServiceImpl { @AutoWired protected UserRepository userRepo; public void createUser(User user) { userRepo.save(user); } }
  • 20. Spring Data Sample – Finders public interface UserRepository extends CrudRepository<User, Long> { List<User> findByGender(String genderCode); List<User> findByDateOfBirthBetween( Date startDate, Date endDate); } ● Crud Repository provides query predicates based on method name like: findByNameOrderByDateOfBirthDesc findByNameAndGender ● Finder method tokens ● And, Or, Is, Equals, Between, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, After, Before, IsNull, IsNotNull, NotNull, Like, NotLike, StartingWith, EndingWith, Containing, Not, In, NotIn, True, False, IgnoreCase
  • 21. Spring Data Query ● Specific to technology ● Annotated finder method @Query("select * from User u where u.gender = ?") List<User> findUsersForGender(String code) Getters and Setters removed for brevity
  • 22. Spring Data Sample – QueryDSL @Entity @QueryEntity public class User { @Id private Long id; private String fullName; private String gender; private Date dateOfBirth; } ● QueryDSL generates QUser for creating type-safe query. class UserRepository extends QueryDslPredicateExecutor<User>, CrudRepository<User,Long> { } import static Quser.*; List<User> users = userRepo.findAll(user.gender.eq('M')); List<User> users = userRepo.findAll(user.fullName.like("%abc%"));
  • 23. Spring Data – Paging and Sorting class UserRepository extends PagingAndSortingRepository<User, Long> { } ... Pageble page = new PageRequest(1,20); Page<User> users = userRepo.findAll(user.gender.eq("M"), page); ● Create Pageable in UI and add to method. ● Add Pageble to finders ● Add Sort to finders ● Page<User> can be used to retrieve pages. ● Slice<User> can only retrieve next slice.
  • 24. Spring Data – Notes ● Shared code for multiple technologies like MongoDB, JPA, Neo4J etc. ● Entity Mapping is usually specific to technology. ● Common Repository methods can be implemented. ● Paging and Sorting support.
  • 25. Spring Data – Demo and Questions ● JPA With Hibernate ● MongoDB ● QueryDSL ● Demo code at https://github.com/corneil/spring-data-demo