SlideShare ist ein Scribd-Unternehmen logo
1 von 66
Downloaden Sie, um offline zu lesen
Lazy	vs.	Eager	Loading	Strategies	
for	JPA	2.1		
Patrycja	Wegrzynowicz	
Java	Day	Kiev	2015
About	Me	
•  15+	professional	experience		
–  SoGware	engineer,	architect,	head	of	soGware	R&D		
•  Author	and	speaker		
–  JavaOne,	Devoxx,	JavaZone,	TheServerSide	Java	
Symposium,	Jazoon,	OOPSLA,	ASE,	others		
•  Finalizing	PhD	in	Computer	Science		
•  Founder	and	CTO	of	Yonita		
–  Bridge	the	gap	between	the	industry	and	the	academia		
–  Automated	detecUon	and	refactoring	of	soGware	defects	
–  Security,	performance,	concurrency,	databases		
•  TwiVer:	@yonlabs
Outline	
•  MoUvaUon	
•  Why?	
–  Expect	unexpected!	
•  What?	
–  Use	cases	and	corner	cases	
–  Hints	on	strategies	
•  How?	
–  JPA	2.1	
•  Conclusion
Database
Database	
The	Mordor	of	Java	Devs
Hibernate JPA Provider
Heads of Hydra
@Entity
public class Hydra {
private Long id;
private List<Head> heads = new ArrayList<Head>();
@Id @GeneratedValue
public Long getId() {...}
protected void setId() {...}
@OneToMany(cascade=CascadeType.ALL)
public List<Head> getHeads() {
return Collections.unmodifiableList(heads);
}
protected void setHeads() {...}
}
// new EntityManager and new transaction: creates and persists the hydra with 3 heads
// new EntityManager and new transaction
Hydra found = em.find(Hydra.class, hydra.getId());
How Many Queries in 2nd Tx?
@Entity
public class Hydra {
private Long id;
private List<Head> heads = new ArrayList<Head>();
@Id @GeneratedValue
public Long getId() {...}
protected void setId() {...}
@OneToMany(cascade=CascadeType.ALL)
public List<Head> getHeads() {
return Collections.unmodifiableList(heads);
}
protected void setHeads() {...}
}
// new EntityManager and new transaction: creates and persists the hydra with 3 heads
// new EntityManager and new transaction
Hydra found = em.find(Hydra.class, hydra.getId());
(a) 1 select
(b) 2 selects
(c) 1+3 selects
(d) 2 selects, 1 delete, 3
inserts
(e) None of the above
How Many Queries in 2nd Tx?
(a) 1 select
(b) 2 selects
(c) 1+3 selects
(d) 2 selects, 1 delete, 3 inserts
(e) None of the above
During commit hibernate checks whether the
collection property is dirty (needs to be re-created)
by comparing Java identities (object references).
Another Look
@Entity
public class Hydra {
private Long id;
private List<Head> heads = new ArrayList<Head>();
@Id @GeneratedValue
public Long getId() {...}
protected void setId() {...}
@OneToMany(cascade=CascadeType.ALL)
public List<Head> getHeads() {
return Collections.unmodifiableList(heads);
}
protected void setHeads() {...}
}
// new EntityManager and new transaction: creates and persists the hydra with 3 heads
// new EntityManager and new transaction
// during find only 1 select (hydra)
Hydra found = em.find(Hydra.class, hydra.getId());
// during commit 1 select (heads),1 delete (heads),3 inserts (heads)
Lessons Learned
• Expect unexpected ;-)
• Prefer field access mappings
• Operate on collection objects returned by
hibernate
–Don’t change collection references unless you know
what you’re doing
Lessons Learned
• Expect unexpected ;-)
• Prefer field access mappings
• Operate on collection objects returned by
hibernate
–Don’t change collection references unless you know
what you’re doing
List<Head> newHeads = new List<>(hydra.getHeads());
Hydra.setHeads(newHeads);
Other Providers?
• EcpliseLink
– 1 select
• Datanucleus
– 1 select
• „A Performance Comparison of JPA Providers”
Lessons Learned
• A lot of depends on a JPA Provider!
• JPA is a spec
– A great spec, but only a spec
– It says what to implement, not how to implement
• You need to tune an application in a concrete
environment
I do love JPA!
I do love JPA!
But as in every relationship we have
our ups and downs.
My Dear JPA and Its Providers 
My Dear JPA and Its Providers 
My Dear JPA and Its Providers 
LisUng	and	ReporUng
LisUng	and	ReporUng	AnU-PaVerns	
•  Different	contexts	
•  Direct	usage	of	an	object-oriented	domain	
model	
•  Too	much	data	loaded	
•  Heavy	processing	on	the	Java	side
ReporUng	AnU-PaVerns	
Example
ReporUng	AnU-PaVerns	
Employee	EnUty	
@Entity
public class Employee {
@Id @GeneratedValue
private Long id;
private String firstName;
private String lastName;
private BigDecimal salary;
private BigDecimal bonus;
@Temporal(TemporalType.DATE)
private Date startDate;
@Temporal(TemporalType.DATE)
private Date endDate;
@ManyToOne @JoinColumn(name = "manager_id")
private Employee manager;
@OneToOne @JoinColumn(name = "address_id")
private Address address;
private String country;
@OneToMany(mappedBy = "owner")
private Collection<Phone> phones;
@ManyToMany(mappedBy = "employees”)
private Collection<Project> projects;
…
}
Sum	of	Salaries	By	Country	
Select	All	(1)	
TypedQuery<Employee> query = em.createQuery(
"SELECT e FROM Employee e", Employee.class);
List<Employee> list = query.getResultList();
// calculate sum of salaries by country
// map: country->sum
Map<String, BigDecimal> results = new HashMap<>();
for (Employee e : list) {
String country = e.getAddress().getCountry();
BigDecimal total = results.get(country);
if (total == null) total = BigDecimal.ZERO;
total = total.add(e.getSalary());
results.put(country, total);
}
Sum	of	Salaries	by	Country	
Select	Join	Fetch	(2)	
TypedQuery<Employee> query = em.createQuery(
"SELECT e FROM Employee e
JOIN FETCH e.address", Employee.class);
List<Employee> list = query.getResultList();
// calculate sum of salaries by country
// map: country->sum
Map<String, BigDecimal> results = new HashMap<>();
for (Employee e : list) {
String country = e.getAddress().getCountry();
BigDecimal total = results.get(country);
if (total == null) total = BigDecimal.ZERO;
total = total.add(e.getSalary());
results.put(country, total);
}
ReporUng	AnU-PaVerns	
ProjecUon	(3)	
Query query = em.createQuery(
"SELECT e.salary, e.address.country
FROM Employee e”);
List<Object[]> list = query.getResultList();
// calculate sum of salaries by country
// map: country->sum
Map<String, BigDecimal> results = new HashMap<>();
for (Object[] e : list) {
String country = (String) e[1];
BigDecimal total = results.get(country);
if (total == null) total = BigDecimal.ZERO;
total = total.add((BigDecimal) e[0]);
results.put(country, total);
}
ReporUng	AnU-PaVerns	
AggregaUon	JPQL	(4)	
Query query = em.createQuery(
"SELECT SUM(e.salary), e.address.country
FROM Employee e
GROUP BY e.address.country”);
List<Object[]> list = query.getResultList();
// already calculated!
ReporUng	AnU-PaVerns	
AggregaUon	SQL	(5)	
Query query = em.createNativeQuery(
"SELECT SUM(e.salary), a.country
FROM employee e
JOIN address a ON e.address_id = a.id
GROUP BY a.country");
List list = query.getResultList();
// already calculated!
Comparison	1-5	
100	000	employees,	EclipseLink	
MySQL	 PostgreSQL	
(1)	Select	all	(N+1)	 25704ms	 18120ms	
(2)	Select	join	fetch	 6211ms	 3954ms	
(3)	ProjecUon	 533ms	 569ms	
(4)	Aggreg.	JPQL	 410ms	 380ms	
(5)	Aggreg.	SQL	 380ms	 409ms
ProjecUon	
JPQL	->	Value	Object	
Query query = em.createQuery(
"SELECT new com.yonita.jpa.vo.EmployeeVO(
e.salary, e.address.country)
FROM Employee e”);
// List<EmployeeVO>
List list = query.getResultList();
ProjecUon	
JPQL	->	Value	Object	
Query query = em.createQuery(
"SELECT new com.yonita.jpa.CountryStatVO(
sum(e.salary), e.address.country)
FROM Employee e
GROUP BY e.address.country"”);
// List<CountryStatVO>
List list = query.getResultList();
ProjecUon	
SQL	->	Value	Object	
@SqlResultSetMapping(
name = "countryStatVO",
classes = {
@ConstructorResult(
targetClass = CountryStatVO.class,
columns = {
@ColumnResult(name = "ssum", type = BigDecimal.class),
@ColumnResult(name = "country", type = String.class)
})
})
ProjecUon	
SQL	->	Value	Object	
Query query = em.createNativeQuery(
"SELECT SUM(e.salary), a.country
FROM employee e
JOIN address a ON e.address_id = a.id
GROUP BY a.country", "countryStatVO");
// List<CountryStatVO>
List list = query.getResultList();
ProjecUon		
Wrap-up	
•  JPA	2.0		
–  Only	JPQL	query	to	directly	produce	a	value	object!	
•  JPA	2.1	
–  JPQL	and	naUve	queries	to	directly	produce	a	value	object!	
•  Managed	object	
–  Sync	with	database	
–  L1/L2	cache	
•  Use	cases	for	Direct	Value	Object	
–  ReporUng,	staUsUcs,	history	
–  Read-only	data,	GUI	data	
–  Performance:	
•  No	need	for	managed	objects	
•  Rich	(or	fat)	managed	objects	
•  Subset	of	aVributes	required	
•  Gain	speed	
•  Offload	an	app	server
AggregaUon	
Wrap-up	
•  JPA	2.0		
–  Selected	aggregaUon	funcUons:	COUNT,	SUM,	AVG,	MIN,	MAX	
•  JPA	2.1	
–  All	funcUon	as	supported	by	a	database	
–  Call	any	database	funcUon	with	new	FUNCTION	keyword	
•  Database-specific	aggregate	funcUons	
–  MS	SQL:	STDEV,	STDEVP,	VAR,	VARP,…	
–  MySQL:	BIT_AND,	BIT_OR,	BIT_XOR,…	
–  Oracle:	MEDIAN,	PERCENTILE,…	
–  More…	
•  Use	cases	
–  ReporUng,	staUsUcs	
–  Performance	
•  Gain	speed	
•  Offload	an	app	server	to	a	database!
Loading Strategy: EAGER for sure!
• We know what we want
– Known range of required data in a future
execution path
• We want a little
– A relatively small entity, no need to divide it into
tiny pieces
Loading strategy: Usually Better
EAGER!
• Network latency to a database
– Lower number of round-trips to a database with
EAGER loading
Loading Strategy: LAZY for sure!
• We don’t know what we want
– Load only required data
– „I’ll think about that tomorrow”
• We want a lot
– Divide and conquer
– Load what’s needed in the first place
Large Objects
• Lazy Property Fetching
• @Basic(fetch = FetchType.LAZY)
• Recommended usage
– Blobs
– Clobs
– Formulas
• Remember about byte-code instrumentation,
– Otherwise will not work
– Silently ignores
Large Objects
• Lazy Property Fetching
• @Basic(fetch = FetchType.LAZY)
• Recommended usage
– Blobs
– Clobs
– Formulas
• Remember about byte-code instrumentation,
– Otherwise will not work
– Silently ignores
Large Objects
• Something smells here
• Do you really need them?
Large Objects
• Something smells here
• Do you really need them?
• But do you really need them?
Large Objects
• Something smells here
• Do you really need them?
• But do you really need them?
• Ponder on your object model and use cases,
otherwise it’s not gonna work
Large Collections
• Divide and conquer!
• Definitely lazy
• You don’t want a really large collection in the
memory
• Batch size
– JPA Provider specific configuration
Hibernate: Plant a Tree
@Entity
public class Forest {
@Id @GeneratedValue
private Long id;
@OneToMany
private Collection<Tree> trees = new HashSet<Tree>();
public void plantTree(Tree tree) {
return trees.add(tree);
}
}
// new EntityManager and new transaction: creates and persists a forest with 10.000 trees
// new EntityManager and new transaction
Tree tree = new Tree(“oak”);
em.persist(tree);
Forest forest = em.find(Forest.class, id);
forest.plantTree(tree);
How Many Queries in 2nd Tx?
@Entity
public class Forest {
@Id @GeneratedValue
private Long id;
@OneToMany
private Collection<Tree> trees = new HashSet<Tree>();
public void plantTree(Tree tree) {
return trees.add(tree);
}
}
// new EntityManager and new transaction: creates and persists a forest with 10.000 trees
// new EntityManager and new transaction
Tree tree = new Tree(“oak”);
em.persist(tree);
Forest forest = em.find(Forest.class, id);
forest.plantTree(tree);
(a) 1 select, 2 inserts
(b) 2 selects, 2 inserts
(c) 2 selects, 1 delete,
10.000+2 inserts
(d) 2 selects, 10.000
deletes, 10.000+2 inserts
(e) Even more ;-)
How Many Queries in 2nd Tx?
(a) 1 select, 2 inserts
(b) 2 selects, 2 inserts
(c) 2 selects, 1 delete, 10.000+2 inserts
(d) 2 selects, 10.000 deletes, 10.000+2 inserts
(e) Even more ;-)
The combination of OneToMany and Collection
enables a bag semantic. That’s why the collection is
re-created.
Plant a Tree Revisited
@Entity
public class Orchard {
@Id @GeneratedValue
private Long id;
@OneToMany
private List<Tree> trees = new ArrayList<Tree>();
public void plantTree(Tree tree) {
return trees.add(tree);
}
}
// creates and persists a forest with 10.000 trees
// new EntityManager and new transaction
Tree tree = new Tree(“apple tree”);
em.persist(tree);
Orchard orchard = em.find(Orchard.class, id);
orchard.plantTree(tree);
STILL BAG SEMANTIC
Use OrderColumn or
IndexColumn for list
semantic.
Plant a Tree
@Entity
public class Forest {
@Id @GeneratedValue
private Long id;
@OneToMany
private Set<Tree> trees = new HashSet<Tree>();
public void plantTree(Tree tree) {
return trees.add(tree);
}
}
// new EntityManager and new transaction: creates and persists a forest with 10.000 trees
// new EntityManager and new transaction
Tree tree = new Tree(“oak”);
em.persist(tree);
Forest forest = em.find(Forest.class, id);
forest.plantTree(tree);
1. Collection elements
loaded into memory
2. Possibly unnecessary
queries
3. Transaction and locking
schema problems:
version, optimistic
locking
Plant a Tree
@Entity public class Forest {
@Id @GeneratedValue
private Long id;
@OneToMany(mappedBy = „forest”)
private Set<Tree> trees = new HashSet<Tree>();
public void plantTree(Tree tree) {
return trees.add(tree);
}
}
@Entity public class Tree {
@Id @GeneratedValue
private Long id;
private String name;
@ManyToOne
private Forest forest;
public void setForest(Forest forest) {
this.forest = forest;
Forest.plantTree(this);
}
}
Set semantic on the
inverse side forces of
loading all trees.
Other Providers?
• EclipseLink
– 2 selects/2 inserts
• OpenJPA
• 3 selects/1 update/2inserts
• Datanucleus
• 3 selects/1 update/2inserts
Loading strategy: It depends!
• You know what you want
– But it’s dynamic, depending on an execution path
and its parameters
Loading strategy: It depends!
• You know what you want
– But it’s dynamic, depending on runtime
parameters
• That was the problem in JPA 2.0
– Fetch queries
– Provider specific extensions
– Different mappings for different cases
• JPA 2.1 comes in handy
Entity Graphs in JPA 2.1
• „A template that captures the paths and
boundaries for an operation or query”
• Fetch plans for query or find operations
• Defined by annotations
• Created programmatically
Entity Graphs in JPA 2.1
• Defined by annotations
– @NamedEntityGraph, @NamedEntitySubgraph,
@NamedAttributeNode
• Created programmatically
– Interfaces EntityGraph, EntitySubgraph,
AttributeNode
Entity Graphs in Query or Find
• Default fetch graph
– Transitive closure of all its attributes specified or
defaulted as EAGER
• javax.persistence.fetchgraph
– Attributes specified by attribute nodes are EAGER,
others are LAZY
• javax.persistence.loadgraph
– Attributes specified by by attribute nodes are
EAGER, others as specified or defaulted
Entity Graphs in Query or Find
• Default fetch graph
– Transitive closure of all its attributes specified or
defaulted as EAGER
• javax.persistence.fetchgraph
– Attributes specified by attribute nodes are EAGER,
others are LAZY
• javax.persistence.loadgraph
– Attributes specified by by attribute nodes are
EAGER, others as specified or defaulted
Entity Graphs in Query or Find
• Default fetch graph
– Transitive closure of all its attributes specified or
defaulted as EAGER
• javax.persistence.fetchgraph
– Attributes specified by attribute nodes are EAGER,
others are LAZY
• javax.persistence.loadgraph
– Attributes specified by by attribute nodes are
EAGER, others as specified or defaulted
Entity Graphs Advantages
• Better hints to JPA providers
• Hibernate now generates smarter queries
– 1 select with joins on 3 tables
– 1 round-trip to a database instead of default N+1
• Dynamic modification of a fetch plan
There is that question...
JPA	2.1
Wrap-up	
•  Main	use	cases	
–  LisUng	and	reporUng	
•  JPA		
–  EnUty	graphs	(JPA	2.1)	
–  ProjecUons	(JPA	2.0/2.1)	
•  Performance	
–  Don’t	load	if	you	don’t	need	
–  Don’t	execute	many	small	queries	if	you	can	execute	one	big	query	
–  Don’t	calculate	if	a	database	can	
•  Tuning	
–  Tune	in	your	concrete	environment		
–  JPA	Providers	behave	differently!	
–  Databases	behave	differently!
ConUnuous	IntegraUon
ConUnuous	Refactoring
ConUnuous	Learning!
ConUnuous	Learning	Paradigm	
•  A	fool	with	a	tool	is	sUll	a	fool	
•  Let’s	educate	ourselves!	J
Q&A	
	
	
patrycja@yonita.com	
@yonlabs

Weitere ähnliche Inhalte

Was ist angesagt?

Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안SANG WON PARK
 
Optimizing RocksDB for Open-Channel SSDs
Optimizing RocksDB for Open-Channel SSDsOptimizing RocksDB for Open-Channel SSDs
Optimizing RocksDB for Open-Channel SSDsJavier González
 
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013mumrah
 
Deploying and Operating KSQL
Deploying and Operating KSQLDeploying and Operating KSQL
Deploying and Operating KSQLconfluent
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producerconfluent
 
Introduction to KSQL: Streaming SQL for Apache Kafka®
Introduction to KSQL: Streaming SQL for Apache Kafka®Introduction to KSQL: Streaming SQL for Apache Kafka®
Introduction to KSQL: Streaming SQL for Apache Kafka®confluent
 
How Apache Kafka® Works
How Apache Kafka® WorksHow Apache Kafka® Works
How Apache Kafka® Worksconfluent
 
Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm Chandler Huang
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
Kafka 101 and Developer Best Practices
Kafka 101 and Developer Best PracticesKafka 101 and Developer Best Practices
Kafka 101 and Developer Best Practicesconfluent
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMike Dirolf
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewShahed Chowdhuri
 
Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache KafkaJeff Holoman
 
Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)Julian Hyde
 
Apache Kafka Fundamentals for Architects, Admins and Developers
Apache Kafka Fundamentals for Architects, Admins and DevelopersApache Kafka Fundamentals for Architects, Admins and Developers
Apache Kafka Fundamentals for Architects, Admins and Developersconfluent
 
Being Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorMax Huang
 

Was ist angesagt? (20)

Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
 
Lucene basics
Lucene basicsLucene basics
Lucene basics
 
Optimizing RocksDB for Open-Channel SSDs
Optimizing RocksDB for Open-Channel SSDsOptimizing RocksDB for Open-Channel SSDs
Optimizing RocksDB for Open-Channel SSDs
 
Real-World NoSQL Schema Design
Real-World NoSQL Schema DesignReal-World NoSQL Schema Design
Real-World NoSQL Schema Design
 
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
Introduction and Overview of Apache Kafka, TriHUG July 23, 2013
 
Deploying and Operating KSQL
Deploying and Operating KSQLDeploying and Operating KSQL
Deploying and Operating KSQL
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Common issues with Apache Kafka® Producer
Common issues with Apache Kafka® ProducerCommon issues with Apache Kafka® Producer
Common issues with Apache Kafka® Producer
 
Introduction to KSQL: Streaming SQL for Apache Kafka®
Introduction to KSQL: Streaming SQL for Apache Kafka®Introduction to KSQL: Streaming SQL for Apache Kafka®
Introduction to KSQL: Streaming SQL for Apache Kafka®
 
How Apache Kafka® Works
How Apache Kafka® WorksHow Apache Kafka® Works
How Apache Kafka® Works
 
Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Kafka 101 and Developer Best Practices
Kafka 101 and Developer Best PracticesKafka 101 and Developer Best Practices
Kafka 101 and Developer Best Practices
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Dot Net Core
Dot Net CoreDot Net Core
Dot Net Core
 
Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache Kafka
 
Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)
 
Apache Kafka Fundamentals for Architects, Admins and Developers
Apache Kafka Fundamentals for Architects, Admins and DevelopersApache Kafka Fundamentals for Architects, Admins and Developers
Apache Kafka Fundamentals for Architects, Admins and Developers
 
Being Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring ReactorBeing Functional on Reactive Streams with Spring Reactor
Being Functional on Reactive Streams with Spring Reactor
 

Andere mochten auch

Secure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EESecure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EEPatrycja Wegrzynowicz
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your developmentStrannik_2013
 
Micro ORM vs Entity Framework
Micro ORM vs Entity FrameworkMicro ORM vs Entity Framework
Micro ORM vs Entity FrameworkAxilis
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Spring.Boot up your development
Spring.Boot up your developmentSpring.Boot up your development
Spring.Boot up your developmentStrannik_2013
 
Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarCraig Dickson
 
Junior,middle,senior?
Junior,middle,senior?Junior,middle,senior?
Junior,middle,senior?Strannik_2013
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewCraig Dickson
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 

Andere mochten auch (20)

Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Hibernate using jpa
Hibernate using jpaHibernate using jpa
Hibernate using jpa
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Secure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EESecure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EE
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your development
 
Micro ORM vs Entity Framework
Micro ORM vs Entity FrameworkMicro ORM vs Entity Framework
Micro ORM vs Entity Framework
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
JPA - Beyond copy-paste
JPA - Beyond copy-pasteJPA - Beyond copy-paste
JPA - Beyond copy-paste
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Spring.Boot up your development
Spring.Boot up your developmentSpring.Boot up your development
Spring.Boot up your development
 
Spring
SpringSpring
Spring
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI Webinar
 
Junior,middle,senior?
Junior,middle,senior?Junior,middle,senior?
Junior,middle,senior?
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 

Ähnlich wie Lazy vs. Eager Loading Strategies in JPA 2.1

Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
Big data week presentation
Big data week presentationBig data week presentation
Big data week presentationJoseph Adler
 
OGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's ViewOGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's ViewBartosz Dobrzelecki
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGvraopolisetti
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)Paul Chao
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profilerIhor Bobak
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
Building Deep Learning Workflows with DL4J
Building Deep Learning Workflows with DL4JBuilding Deep Learning Workflows with DL4J
Building Deep Learning Workflows with DL4JJosh Patterson
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...TAISEEREISA
 

Ähnlich wie Lazy vs. Eager Loading Strategies in JPA 2.1 (20)

Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Big data week presentation
Big data week presentationBig data week presentation
Big data week presentation
 
OGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's ViewOGSA-DAI DQP: A Developer's View
OGSA-DAI DQP: A Developer's View
 
Salesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUGSalesforce Batch processing - Atlanta SFUG
Salesforce Batch processing - Atlanta SFUG
 
Green dao
Green daoGreen dao
Green dao
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Hadoop ecosystem
Hadoop ecosystemHadoop ecosystem
Hadoop ecosystem
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Hadoop ecosystem
Hadoop ecosystemHadoop ecosystem
Hadoop ecosystem
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
Building Deep Learning Workflows with DL4J
Building Deep Learning Workflows with DL4JBuilding Deep Learning Workflows with DL4J
Building Deep Learning Workflows with DL4J
 
Json generation
Json generationJson generation
Json generation
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Dapper performance
Dapper performanceDapper performance
Dapper performance
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 

Mehr von Patrycja Wegrzynowicz

Mehr von Patrycja Wegrzynowicz (9)

The Hacker's Guide to Kubernetes: Reloaded
The Hacker's Guide to Kubernetes: ReloadedThe Hacker's Guide to Kubernetes: Reloaded
The Hacker's Guide to Kubernetes: Reloaded
 
The Hacker's Guide to Kubernetes
The Hacker's Guide to KubernetesThe Hacker's Guide to Kubernetes
The Hacker's Guide to Kubernetes
 
The Hacker's Guide to JWT Security
The Hacker's Guide to JWT SecurityThe Hacker's Guide to JWT Security
The Hacker's Guide to JWT Security
 
The Hacker's Guide to JWT Security
The Hacker's Guide to JWT SecurityThe Hacker's Guide to JWT Security
The Hacker's Guide to JWT Security
 
The Hacker's Guide to XSS
The Hacker's Guide to XSSThe Hacker's Guide to XSS
The Hacker's Guide to XSS
 
The Hacker's Guide to NoSQL Injection
The Hacker's Guide to NoSQL InjectionThe Hacker's Guide to NoSQL Injection
The Hacker's Guide to NoSQL Injection
 
The Hacker's Guide to Session Hijacking
The Hacker's Guide to Session Hijacking The Hacker's Guide to Session Hijacking
The Hacker's Guide to Session Hijacking
 
The Hacker's Guide To Session Hijacking
The Hacker's Guide To Session HijackingThe Hacker's Guide To Session Hijacking
The Hacker's Guide To Session Hijacking
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 

Kürzlich hochgeladen

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Kürzlich hochgeladen (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Lazy vs. Eager Loading Strategies in JPA 2.1

  • 2. About Me •  15+ professional experience –  SoGware engineer, architect, head of soGware R&D •  Author and speaker –  JavaOne, Devoxx, JavaZone, TheServerSide Java Symposium, Jazoon, OOPSLA, ASE, others •  Finalizing PhD in Computer Science •  Founder and CTO of Yonita –  Bridge the gap between the industry and the academia –  Automated detecUon and refactoring of soGware defects –  Security, performance, concurrency, databases •  TwiVer: @yonlabs
  • 3. Outline •  MoUvaUon •  Why? –  Expect unexpected! •  What? –  Use cases and corner cases –  Hints on strategies •  How? –  JPA 2.1 •  Conclusion
  • 6. Hibernate JPA Provider Heads of Hydra @Entity public class Hydra { private Long id; private List<Head> heads = new ArrayList<Head>(); @Id @GeneratedValue public Long getId() {...} protected void setId() {...} @OneToMany(cascade=CascadeType.ALL) public List<Head> getHeads() { return Collections.unmodifiableList(heads); } protected void setHeads() {...} } // new EntityManager and new transaction: creates and persists the hydra with 3 heads // new EntityManager and new transaction Hydra found = em.find(Hydra.class, hydra.getId());
  • 7. How Many Queries in 2nd Tx? @Entity public class Hydra { private Long id; private List<Head> heads = new ArrayList<Head>(); @Id @GeneratedValue public Long getId() {...} protected void setId() {...} @OneToMany(cascade=CascadeType.ALL) public List<Head> getHeads() { return Collections.unmodifiableList(heads); } protected void setHeads() {...} } // new EntityManager and new transaction: creates and persists the hydra with 3 heads // new EntityManager and new transaction Hydra found = em.find(Hydra.class, hydra.getId()); (a) 1 select (b) 2 selects (c) 1+3 selects (d) 2 selects, 1 delete, 3 inserts (e) None of the above
  • 8. How Many Queries in 2nd Tx? (a) 1 select (b) 2 selects (c) 1+3 selects (d) 2 selects, 1 delete, 3 inserts (e) None of the above During commit hibernate checks whether the collection property is dirty (needs to be re-created) by comparing Java identities (object references).
  • 9. Another Look @Entity public class Hydra { private Long id; private List<Head> heads = new ArrayList<Head>(); @Id @GeneratedValue public Long getId() {...} protected void setId() {...} @OneToMany(cascade=CascadeType.ALL) public List<Head> getHeads() { return Collections.unmodifiableList(heads); } protected void setHeads() {...} } // new EntityManager and new transaction: creates and persists the hydra with 3 heads // new EntityManager and new transaction // during find only 1 select (hydra) Hydra found = em.find(Hydra.class, hydra.getId()); // during commit 1 select (heads),1 delete (heads),3 inserts (heads)
  • 10. Lessons Learned • Expect unexpected ;-) • Prefer field access mappings • Operate on collection objects returned by hibernate –Don’t change collection references unless you know what you’re doing
  • 11. Lessons Learned • Expect unexpected ;-) • Prefer field access mappings • Operate on collection objects returned by hibernate –Don’t change collection references unless you know what you’re doing List<Head> newHeads = new List<>(hydra.getHeads()); Hydra.setHeads(newHeads);
  • 12. Other Providers? • EcpliseLink – 1 select • Datanucleus – 1 select • „A Performance Comparison of JPA Providers”
  • 13. Lessons Learned • A lot of depends on a JPA Provider! • JPA is a spec – A great spec, but only a spec – It says what to implement, not how to implement • You need to tune an application in a concrete environment
  • 14. I do love JPA!
  • 15. I do love JPA! But as in every relationship we have our ups and downs.
  • 16. My Dear JPA and Its Providers 
  • 17. My Dear JPA and Its Providers 
  • 18. My Dear JPA and Its Providers 
  • 22. ReporUng AnU-PaVerns Employee EnUty @Entity public class Employee { @Id @GeneratedValue private Long id; private String firstName; private String lastName; private BigDecimal salary; private BigDecimal bonus; @Temporal(TemporalType.DATE) private Date startDate; @Temporal(TemporalType.DATE) private Date endDate; @ManyToOne @JoinColumn(name = "manager_id") private Employee manager; @OneToOne @JoinColumn(name = "address_id") private Address address; private String country; @OneToMany(mappedBy = "owner") private Collection<Phone> phones; @ManyToMany(mappedBy = "employees”) private Collection<Project> projects; … }
  • 23. Sum of Salaries By Country Select All (1) TypedQuery<Employee> query = em.createQuery( "SELECT e FROM Employee e", Employee.class); List<Employee> list = query.getResultList(); // calculate sum of salaries by country // map: country->sum Map<String, BigDecimal> results = new HashMap<>(); for (Employee e : list) { String country = e.getAddress().getCountry(); BigDecimal total = results.get(country); if (total == null) total = BigDecimal.ZERO; total = total.add(e.getSalary()); results.put(country, total); }
  • 24. Sum of Salaries by Country Select Join Fetch (2) TypedQuery<Employee> query = em.createQuery( "SELECT e FROM Employee e JOIN FETCH e.address", Employee.class); List<Employee> list = query.getResultList(); // calculate sum of salaries by country // map: country->sum Map<String, BigDecimal> results = new HashMap<>(); for (Employee e : list) { String country = e.getAddress().getCountry(); BigDecimal total = results.get(country); if (total == null) total = BigDecimal.ZERO; total = total.add(e.getSalary()); results.put(country, total); }
  • 25. ReporUng AnU-PaVerns ProjecUon (3) Query query = em.createQuery( "SELECT e.salary, e.address.country FROM Employee e”); List<Object[]> list = query.getResultList(); // calculate sum of salaries by country // map: country->sum Map<String, BigDecimal> results = new HashMap<>(); for (Object[] e : list) { String country = (String) e[1]; BigDecimal total = results.get(country); if (total == null) total = BigDecimal.ZERO; total = total.add((BigDecimal) e[0]); results.put(country, total); }
  • 26. ReporUng AnU-PaVerns AggregaUon JPQL (4) Query query = em.createQuery( "SELECT SUM(e.salary), e.address.country FROM Employee e GROUP BY e.address.country”); List<Object[]> list = query.getResultList(); // already calculated!
  • 27. ReporUng AnU-PaVerns AggregaUon SQL (5) Query query = em.createNativeQuery( "SELECT SUM(e.salary), a.country FROM employee e JOIN address a ON e.address_id = a.id GROUP BY a.country"); List list = query.getResultList(); // already calculated!
  • 28. Comparison 1-5 100 000 employees, EclipseLink MySQL PostgreSQL (1) Select all (N+1) 25704ms 18120ms (2) Select join fetch 6211ms 3954ms (3) ProjecUon 533ms 569ms (4) Aggreg. JPQL 410ms 380ms (5) Aggreg. SQL 380ms 409ms
  • 29. ProjecUon JPQL -> Value Object Query query = em.createQuery( "SELECT new com.yonita.jpa.vo.EmployeeVO( e.salary, e.address.country) FROM Employee e”); // List<EmployeeVO> List list = query.getResultList();
  • 30. ProjecUon JPQL -> Value Object Query query = em.createQuery( "SELECT new com.yonita.jpa.CountryStatVO( sum(e.salary), e.address.country) FROM Employee e GROUP BY e.address.country"”); // List<CountryStatVO> List list = query.getResultList();
  • 31. ProjecUon SQL -> Value Object @SqlResultSetMapping( name = "countryStatVO", classes = { @ConstructorResult( targetClass = CountryStatVO.class, columns = { @ColumnResult(name = "ssum", type = BigDecimal.class), @ColumnResult(name = "country", type = String.class) }) })
  • 32. ProjecUon SQL -> Value Object Query query = em.createNativeQuery( "SELECT SUM(e.salary), a.country FROM employee e JOIN address a ON e.address_id = a.id GROUP BY a.country", "countryStatVO"); // List<CountryStatVO> List list = query.getResultList();
  • 33. ProjecUon Wrap-up •  JPA 2.0 –  Only JPQL query to directly produce a value object! •  JPA 2.1 –  JPQL and naUve queries to directly produce a value object! •  Managed object –  Sync with database –  L1/L2 cache •  Use cases for Direct Value Object –  ReporUng, staUsUcs, history –  Read-only data, GUI data –  Performance: •  No need for managed objects •  Rich (or fat) managed objects •  Subset of aVributes required •  Gain speed •  Offload an app server
  • 34. AggregaUon Wrap-up •  JPA 2.0 –  Selected aggregaUon funcUons: COUNT, SUM, AVG, MIN, MAX •  JPA 2.1 –  All funcUon as supported by a database –  Call any database funcUon with new FUNCTION keyword •  Database-specific aggregate funcUons –  MS SQL: STDEV, STDEVP, VAR, VARP,… –  MySQL: BIT_AND, BIT_OR, BIT_XOR,… –  Oracle: MEDIAN, PERCENTILE,… –  More… •  Use cases –  ReporUng, staUsUcs –  Performance •  Gain speed •  Offload an app server to a database!
  • 35. Loading Strategy: EAGER for sure! • We know what we want – Known range of required data in a future execution path • We want a little – A relatively small entity, no need to divide it into tiny pieces
  • 36. Loading strategy: Usually Better EAGER! • Network latency to a database – Lower number of round-trips to a database with EAGER loading
  • 37. Loading Strategy: LAZY for sure! • We don’t know what we want – Load only required data – „I’ll think about that tomorrow” • We want a lot – Divide and conquer – Load what’s needed in the first place
  • 38. Large Objects • Lazy Property Fetching • @Basic(fetch = FetchType.LAZY) • Recommended usage – Blobs – Clobs – Formulas • Remember about byte-code instrumentation, – Otherwise will not work – Silently ignores
  • 39. Large Objects • Lazy Property Fetching • @Basic(fetch = FetchType.LAZY) • Recommended usage – Blobs – Clobs – Formulas • Remember about byte-code instrumentation, – Otherwise will not work – Silently ignores
  • 40. Large Objects • Something smells here • Do you really need them?
  • 41. Large Objects • Something smells here • Do you really need them? • But do you really need them?
  • 42. Large Objects • Something smells here • Do you really need them? • But do you really need them? • Ponder on your object model and use cases, otherwise it’s not gonna work
  • 43. Large Collections • Divide and conquer! • Definitely lazy • You don’t want a really large collection in the memory • Batch size – JPA Provider specific configuration
  • 44. Hibernate: Plant a Tree @Entity public class Forest { @Id @GeneratedValue private Long id; @OneToMany private Collection<Tree> trees = new HashSet<Tree>(); public void plantTree(Tree tree) { return trees.add(tree); } } // new EntityManager and new transaction: creates and persists a forest with 10.000 trees // new EntityManager and new transaction Tree tree = new Tree(“oak”); em.persist(tree); Forest forest = em.find(Forest.class, id); forest.plantTree(tree);
  • 45. How Many Queries in 2nd Tx? @Entity public class Forest { @Id @GeneratedValue private Long id; @OneToMany private Collection<Tree> trees = new HashSet<Tree>(); public void plantTree(Tree tree) { return trees.add(tree); } } // new EntityManager and new transaction: creates and persists a forest with 10.000 trees // new EntityManager and new transaction Tree tree = new Tree(“oak”); em.persist(tree); Forest forest = em.find(Forest.class, id); forest.plantTree(tree); (a) 1 select, 2 inserts (b) 2 selects, 2 inserts (c) 2 selects, 1 delete, 10.000+2 inserts (d) 2 selects, 10.000 deletes, 10.000+2 inserts (e) Even more ;-)
  • 46. How Many Queries in 2nd Tx? (a) 1 select, 2 inserts (b) 2 selects, 2 inserts (c) 2 selects, 1 delete, 10.000+2 inserts (d) 2 selects, 10.000 deletes, 10.000+2 inserts (e) Even more ;-) The combination of OneToMany and Collection enables a bag semantic. That’s why the collection is re-created.
  • 47. Plant a Tree Revisited @Entity public class Orchard { @Id @GeneratedValue private Long id; @OneToMany private List<Tree> trees = new ArrayList<Tree>(); public void plantTree(Tree tree) { return trees.add(tree); } } // creates and persists a forest with 10.000 trees // new EntityManager and new transaction Tree tree = new Tree(“apple tree”); em.persist(tree); Orchard orchard = em.find(Orchard.class, id); orchard.plantTree(tree); STILL BAG SEMANTIC Use OrderColumn or IndexColumn for list semantic.
  • 48. Plant a Tree @Entity public class Forest { @Id @GeneratedValue private Long id; @OneToMany private Set<Tree> trees = new HashSet<Tree>(); public void plantTree(Tree tree) { return trees.add(tree); } } // new EntityManager and new transaction: creates and persists a forest with 10.000 trees // new EntityManager and new transaction Tree tree = new Tree(“oak”); em.persist(tree); Forest forest = em.find(Forest.class, id); forest.plantTree(tree); 1. Collection elements loaded into memory 2. Possibly unnecessary queries 3. Transaction and locking schema problems: version, optimistic locking
  • 49. Plant a Tree @Entity public class Forest { @Id @GeneratedValue private Long id; @OneToMany(mappedBy = „forest”) private Set<Tree> trees = new HashSet<Tree>(); public void plantTree(Tree tree) { return trees.add(tree); } } @Entity public class Tree { @Id @GeneratedValue private Long id; private String name; @ManyToOne private Forest forest; public void setForest(Forest forest) { this.forest = forest; Forest.plantTree(this); } } Set semantic on the inverse side forces of loading all trees.
  • 50. Other Providers? • EclipseLink – 2 selects/2 inserts • OpenJPA • 3 selects/1 update/2inserts • Datanucleus • 3 selects/1 update/2inserts
  • 51. Loading strategy: It depends! • You know what you want – But it’s dynamic, depending on an execution path and its parameters
  • 52. Loading strategy: It depends! • You know what you want – But it’s dynamic, depending on runtime parameters • That was the problem in JPA 2.0 – Fetch queries – Provider specific extensions – Different mappings for different cases • JPA 2.1 comes in handy
  • 53. Entity Graphs in JPA 2.1 • „A template that captures the paths and boundaries for an operation or query” • Fetch plans for query or find operations • Defined by annotations • Created programmatically
  • 54. Entity Graphs in JPA 2.1 • Defined by annotations – @NamedEntityGraph, @NamedEntitySubgraph, @NamedAttributeNode • Created programmatically – Interfaces EntityGraph, EntitySubgraph, AttributeNode
  • 55. Entity Graphs in Query or Find • Default fetch graph – Transitive closure of all its attributes specified or defaulted as EAGER • javax.persistence.fetchgraph – Attributes specified by attribute nodes are EAGER, others are LAZY • javax.persistence.loadgraph – Attributes specified by by attribute nodes are EAGER, others as specified or defaulted
  • 56. Entity Graphs in Query or Find • Default fetch graph – Transitive closure of all its attributes specified or defaulted as EAGER • javax.persistence.fetchgraph – Attributes specified by attribute nodes are EAGER, others are LAZY • javax.persistence.loadgraph – Attributes specified by by attribute nodes are EAGER, others as specified or defaulted
  • 57. Entity Graphs in Query or Find • Default fetch graph – Transitive closure of all its attributes specified or defaulted as EAGER • javax.persistence.fetchgraph – Attributes specified by attribute nodes are EAGER, others are LAZY • javax.persistence.loadgraph – Attributes specified by by attribute nodes are EAGER, others as specified or defaulted
  • 58. Entity Graphs Advantages • Better hints to JPA providers • Hibernate now generates smarter queries – 1 select with joins on 3 tables – 1 round-trip to a database instead of default N+1 • Dynamic modification of a fetch plan
  • 59. There is that question...
  • 61. Wrap-up •  Main use cases –  LisUng and reporUng •  JPA –  EnUty graphs (JPA 2.1) –  ProjecUons (JPA 2.0/2.1) •  Performance –  Don’t load if you don’t need –  Don’t execute many small queries if you can execute one big query –  Don’t calculate if a database can •  Tuning –  Tune in your concrete environment –  JPA Providers behave differently! –  Databases behave differently!