SlideShare a Scribd company logo
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

More Related Content

What's hot

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
Andrei Sebastian Cîmpean
 
Getting started with node JS
Getting started with node JSGetting started with node JS
Getting started with node JS
Hamdi Hmidi
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
Make School
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
All 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 logging
Tricode (part of Dept)
 
Indexed db
Indexed dbIndexed db
Indexed db
Martin Giger
 
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
GWTcon
 
ReactJS for Beginners
ReactJS for BeginnersReactJS for Beginners
ReactJS for Beginners
Oswald Campesato
 
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
 
React & Redux
React & ReduxReact & Redux
React & Redux
Federico Bond
 
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 for Beginners
React for BeginnersReact for Beginners
React for Beginners
Derek Willian Stavis
 
React JS and Redux
React JS and ReduxReact JS and Redux
React JS and Redux
Glib Kechyn
 
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
Ny Fanilo Andrianjafy, B.Eng.
 
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 10mins
zmcartor
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
NexThoughts Technologies
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
FITC
 

What's hot (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
 

Similar to Polyglot persistence with Spring Data

Five android architecture
Five android architectureFive android architecture
Five android architecture
Tomislav Homan
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
sourabh 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 Galkin
Sigma Software
 
ORM JPA
ORM JPAORM JPA
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
Timo Westkämper
 
PHP BASIC PRESENTATION
PHP BASIC PRESENTATIONPHP BASIC PRESENTATION
PHP BASIC PRESENTATION
krutitrivedi
 
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
Ahmad Arif Faizin
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
Staples
 
Spring.io
Spring.ioSpring.io
Spring.io
Cédric GILLET
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
Jonathan Felch
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
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 Java
MongoDB
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Sqladria 2009 SRC
Sqladria 2009 SRCSqladria 2009 SRC
Sqladria 2009 SRC
tepsum
 
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...
National Information Standards Organization (NISO)
 
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
Katie Gulley
 

Similar to 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
 

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 Workshop
Corneil du Plessis
 
QueryDSL - Lightning Talk
QueryDSL - Lightning TalkQueryDSL - Lightning Talk
QueryDSL - Lightning Talk
Corneil du Plessis
 
Enhancements in Java 9 Streams
Enhancements in Java 9 StreamsEnhancements in Java 9 Streams
Enhancements in Java 9 Streams
Corneil du Plessis
 
Reactive Spring 5
Reactive Spring 5Reactive Spring 5
Reactive Spring 5
Corneil du Plessis
 
Empathic API-Design
Empathic API-DesignEmpathic API-Design
Empathic API-Design
Corneil du Plessis
 
Performance Comparison JVM Languages
Performance Comparison JVM LanguagesPerformance Comparison JVM Languages
Performance Comparison JVM Languages
Corneil du Plessis
 
Microservices Patterns and Anti-Patterns
Microservices Patterns and Anti-PatternsMicroservices Patterns and Anti-Patterns
Microservices Patterns and Anti-Patterns
Corneil du Plessis
 
Consume Spring Data Rest with Angularjs
Consume Spring Data Rest with AngularjsConsume Spring Data Rest with Angularjs
Consume Spring Data Rest with Angularjs
Corneil du Plessis
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
Corneil 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
 
Data repositories
Data repositoriesData repositories
Data repositories
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 for
Corneil 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 (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
 

Recently uploaded

Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 

Recently uploaded (20)

Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 

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