SlideShare a Scribd company logo
1 of 72
Download to read offline
Second-­‐Level	
  Cache	
  	
  
in	
  JPA	
  Explained
Patrycja	
  Wegrzynowicz	
  
CTO,	
  Yonita,	
  Inc.	
  
JavaOne	
  2016
About	
  Me
• 15+	
  professional	
  experience	
  	
  
• SoPware	
  engineer,	
  architect,	
  head	
  of	
  
soPware	
  R&D	
  	
  
• Author	
  and	
  speaker	
  	
  
• JavaOne,	
  Devoxx,	
  JavaZone,	
  
TheServerSide	
  Java	
  Symposium,	
  Jazoon,	
  
OOPSLA,	
  ASE,	
  others	
  	
  
• Top	
  10	
  Women	
  in	
  Tech	
  2016	
  in	
  Poland	
  
• Founder	
  and	
  CTO	
  of	
  Yonita	
  
• Automated	
  detecXon	
  and	
  refactoring	
  of	
  
soPware	
  defects	
  
• Trainings	
  and	
  code	
  reviews	
  
• Security,	
  performance,	
  concurrency,	
  
databases	
  	
  
• TwiYer	
  @yonlabs	
  
About	
  Me
• 15+	
  professional	
  experience	
  	
  
• SoPware	
  engineer,	
  architect,	
  head	
  of	
  
soPware	
  R&D	
  	
  
• Author	
  and	
  speaker	
  	
  
• JavaOne,	
  Devoxx,	
  JavaZone,	
  
TheServerSide	
  Java	
  Symposium,	
  Jazoon,	
  
OOPSLA,	
  ASE,	
  others	
  	
  
• Top	
  10	
  Women	
  in	
  Tech	
  2016	
  in	
  Poland	
  
• Founder	
  and	
  CTO	
  of	
  Yonita	
  
• Automated	
  detecXon	
  and	
  refactoring	
  of	
  
soPware	
  defects	
  
• Trainings	
  and	
  code	
  reviews	
  
• Security,	
  performance,	
  concurrency,	
  
databases	
  	
  
• TwiYer	
  @yonlabs	
  
Agenda
• Why	
  cacheing	
  is	
  important?	
  
• 1st	
  Level	
  Cache	
  and	
  2nd	
  Level	
  Cache	
  
• JPA	
  configuraXon	
  parameters	
  for	
  cache	
  
• JPA	
  API	
  for	
  cache	
  
• Hibernate	
  2nd	
  Level	
  Cache	
  
• EclipseLink	
  2nd	
  Level	
  Cache	
  (a	
  bit)
Databases
Databases
Performance
Request	
  Handling
Performance:	
  Throughput
Performance:	
  ExecuXon	
  Time
Performance:	
  Latency
Performance:	
  Response	
  Time
Example
Employee	
  Entity
@Entity public class Employee {

@Id @GeneratedValue
private Long id;

private String firstName; 

private String lastName;

private BigDecimal salary;

@OneToOne @JoinColumn(name = "address_id")

private Address address;

@Temporal(TemporalType.DATE)

private Date startDate;

@Temporal(TemporalType.DATE)

private Date endDate; 

@ManyToOne @JoinColumn(name = "manager_id")

private Employee manager;
// …

}
14
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);

}

15
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);

}

16
Sum	
  of	
  Salaries	
  by	
  Country

Projection	
  (3)
Query query = em.createQuery(
"SELECT e.salary, e.address.country
FROM Employee e");

List<Object[]> list = (List<Object[]>) 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);

}

17
Sum	
  of	
  Salaries	
  by	
  Country

Aggregation	
  JPQL	
  (4)
Query query = em.createQuery(
"SELECT SUM(e.salary), e.address.country
FROM Employee e
GROUP BY e.address.country");
List<Object[]> list = (List<Object[]>) query.getResultList();

// already calculated!

18
Comparison	
  1-­‐4	
  (Hibernate)	
  
100000	
  Employees,	
  Different	
  DB	
  LocaXons
Local DB
(ping: ~0.05ms)
North California
(ping: ~38ms)
EU Frankfurt
(ping: ~420ms)
(1) Select All
(N+1)
26756ms 2-3 hours ~1 day
(2) Select Join
Fetch
(3) Projection
(4) Aggregation
JPQL
Comparison	
  1-­‐4	
  
100000	
  Employees,	
  Different	
  DB	
  LocaXons
Local DB
(ping: ~0.05ms)
North California
(ping: ~38ms)
EU Frankfurt
(ping: ~420ms)
(1) Select All
(N+1)
26756ms 2-3 hours ~1 day
(2) Select Join
Fetch
4854ms 18027ms 25096ms
(3) Projection
(4) Aggregation
JPQL
Comparison	
  1-­‐4	
  
100000	
  Employees,	
  Different	
  DB	
  LocaXons
Local DB
(ping: ~0.05ms)
North California
(ping: ~38ms)
EU Frankfurt
(ping: ~420ms)
(1) Select All
(N+1)
26756ms 2-3 hours ~1 day
(2) Select Join
Fetch
4854ms 18027ms 25096ms
(3) Projection 653ms 2902ms 5006ms
(4) Aggregation
JPQL
Comparison	
  1-­‐4	
  
100000	
  Employees,	
  Different	
  DB	
  LocaXons
Local DB
(ping: ~0.05ms)
North California
(ping: ~38ms)
EU Frankfurt
(ping: ~420ms)
(1) Select All
(N+1)
26756ms 2-3 hours ~1 day
(2) Select Join
Fetch
4854ms 18027ms 25096ms
(3) Projection 653ms 2902ms 5006ms
(4) Aggregation
JPQL
182ms 353ms 1198ms
Performance	
  Tuning:	
  Data
• Get	
  your	
  data	
  in	
  bigger	
  chunks	
  	
  
• Many	
  small	
  queries	
  =>	
  many	
  round-­‐trips	
  =>	
  huge	
  extra	
  Xme	
  on	
  
transport	
  =>	
  high	
  latency	
  
• Move	
  your	
  data	
  closer	
  to	
  the	
  processing	
  place	
  
• Large	
  distance	
  to	
  data	
  =>	
  long	
  round-­‐trip	
  =>	
  high	
  latency	
  
• Don’t	
  ask	
  about	
  the	
  same	
  data	
  many	
  Xmes	
  
• Extra	
  processing	
  Xme	
  +	
  extra	
  transport	
  Xme
Cache
Cache	
  is	
  Everywhere
Web Cache
Application Cache
RDBMS Cache
DNS Cache
OS Files Cache
Second	
  Level	
  Cache	
  in	
  
JPA
JPA	
  Spec
• “Persistence	
  providers	
  are	
  not	
  required	
  to	
  support	
  a	
  
second-­‐level	
  cache.”	
  
• “Portable	
  applicaXons	
  should	
  not	
  rely	
  on	
  support	
  by	
  
persistence	
  providers	
  for	
  a	
  second-­‐level	
  cache.”
JPA	
  Providers	
  Poll
A. Hibernate	
  
B. EclipseLink	
  
C. OpenJPA	
  
D. DataNuclues	
  
E. Other
• Second	
  Level	
  Cache	
  
• Persistence	
  Unit	
  
• EnXtyManagerFactory	
  
• Thread-­‐safe,	
  shared	
  
• Available	
  for	
  many	
  en1ty	
  
managers	
  from	
  one	
  en1ty	
  
manager	
  factory	
  
• Provider	
  specific	
  support
JPA	
  Caches
• First	
  Level	
  Cache	
  
• Persistence	
  Context	
  
• EnXtyManager	
  
• Not	
  thread-­‐safe	
  
• Available	
  for	
  many	
  
transac1ons	
  on	
  one	
  en1ty	
  
manager	
  
• Always
EnXtyManagerFactory
EntityManagerFactory
creates
creates
creates2LC
EntityManager
1LC
EntityManager
1LC
EntityManager
1LC
Puzzle	
  #1
em.getTransaction().begin();

Employee employee = em.find(Employee.class, 2L);

employee.getAddress().size();
Employee another = em.find(Employee.class, 2L);

em.getTransaction().commit();

(A) No cache used
(B) First Level Cache Used
(C) Second Level Cache Used
(D) None of the above
30
Loading
EntityManager
Factory
2LC
EntityManager
1LC
load from 1LC load from 2LC
select from
database
NOT FOUND NOT FOUND
FOUND FOUND RESULT
FIND
Puzzle	
  #1
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

Employee employee = em.find(Employee.class, 2L);

employee.getAddress().size();
Employee another = em.find(Employee.class, 2L);

em.getTransaction().commit();

(A) No cache used
(B) First Level Cache Used
(C) Second Level Cache Used
(D) None of the above
32
Puzzle	
  #1
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

Employee employee = em.find(Employee.class, 2L);

employee.getAddress().size();
Employee another = em.find(Employee.class, 2L);

em.getTransaction().commit();

(A) No cache used
(B) First Level Cache Used
(C) Second Level Cache Used
(D) None of the above
33
Puzzle	
  #2
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();

EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();

Employee employee = em2.find(Employee.class, 2L);

employee.getAddress().size();
em2.getTransaction().commit();

(A) No cache used
(B) First Level Cache used
(C) Second Level Cache used
(D) None of the above
34
Puzzle	
  #2
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();

EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();

Employee employee = em2.find(Employee.class, 2L);

employee.getAddress().size();
em2.getTransaction().commit();

(A) No cache used
(B) First Level Cache used
(C) Second Level Cache used
(D) None of the above
35
Puzzle	
  #3	
  (2LC	
  Configured,	
  
Hibernate)
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();

EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();

Employee employee = em2.find(Employee.class, 2L);

employee.getAddress().size();
em2.getTransaction().commit();

(A) No cache used
(B) First Level Cache used
(C) Second Level Cache used
(D) None of the above
36
Puzzle	
  #3	
  (2LC	
  Configured,	
  
Hibernate)
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();

EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();

Employee employee = em2.find(Employee.class, 2L);

employee.getAddress().size();
em2.getTransaction().commit();

(A) No cache used
(B) First Level Cache used
(C) Second Level Cache used
(D) None of the above
37
Puzzle	
  #4	
  (2LC	
  Configured!)
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();
a
em2.getTransaction().begin();

TypedQuery<Employee> q =
em.createQuery("SELECT e FROM Employee e WHERE e.id=:id", Employee.class);
q.setParameter("id", 2l);

Employee employee = q.getSingleResult();
employee.getAddress().size();
em2.getTransaction().commit();


(A) No cache used
(B) First Level Cache used
(C) Second Level Cache used
(D) None of the above 38
Puzzle	
  #4	
  (2LC	
  Configured!)
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();
a
em2.getTransaction().begin();

TypedQuery<Employee> q =
em.createQuery("SELECT e FROM Employee e WHERE e.id=:id", Employee.class);
q.setParameter("id", 2l);

Employee employee = q.getSingleResult();
employee.getAddress().size();
em2.getTransaction().commit();


(A) No cache used
(B) First Level Cache used
(C) Second Level Cache used
(D) None of the above 39
persistence.xml
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>

40
Programmatic	
  
Properties props = new Properties()
.add(“javax.persistence.sharedCache.mode”, “ENABLE_SELECTIVE”);
EntityManagerFactor emf = Persistence
.createEntityManagerFactory(“test-pu”, props);
41
JPA	
  Cache	
  Modes
• ALL	
  
• All	
  enXty	
  data	
  is	
  stored	
  in	
  the	
  second-­‐level	
  cache	
  for	
  this	
  persistence	
  unit.	
   	
  
• NONE	
   	
  
• No	
  data	
  is	
  cached	
  in	
  the	
  persistence	
  unit.	
  The	
  persistence	
  provider	
  must	
  not	
  cache	
  any	
  
data.	
  
• ENABLE_SELECTIVE	
   	
  
• Enable	
  caching	
  for	
  enXXes	
  that	
  have	
  been	
  explicitly	
  set	
  with	
  the	
  @Cacheable	
  annotaXon.	
  
• DISABLE_SELECTIVE	
  	
  
• Enable	
  caching	
  for	
  all	
  enXXes	
  except	
  those	
  that	
  have	
  been	
  explicitly	
  set	
  with	
  the	
  
@Cacheable(false)	
  annotaXon.	
   	
  
• UNSPECIFIED	
   	
  
• The	
  caching	
  behavior	
  for	
  the	
  persistence	
  unit	
  is	
  undefined.	
  The	
  persistence	
  provider’s	
  
default	
  caching	
  behavior	
  will	
  be	
  used.
JPA	
  Cache	
  Modes
• ALL	
  
• All	
  enXty	
  data	
  is	
  stored	
  in	
  the	
  second-­‐level	
  cache	
  for	
  this	
  persistence	
  unit.	
   	
  
• NONE	
   	
  
• No	
  data	
  is	
  cached	
  in	
  the	
  persistence	
  unit.	
  The	
  persistence	
  provider	
  must	
  not	
  cache	
  any	
  
data.	
  
• ENABLE_SELECTIVE	
   	
  
• Enable	
  caching	
  for	
  enXXes	
  that	
  have	
  been	
  explicitly	
  set	
  with	
  the	
  @Cacheable	
  annotaXon.	
  
• DISABLE_SELECTIVE	
  	
  
• Enable	
  caching	
  for	
  all	
  enXXes	
  except	
  those	
  that	
  have	
  been	
  explicitly	
  set	
  with	
  the	
  
@Cacheable(false)	
  annotaXon.	
   	
  
• UNSPECIFIED	
   	
  
• The	
  caching	
  behavior	
  for	
  the	
  persistence	
  unit	
  is	
  undefined.	
  The	
  persistence	
  provider’s	
  
default	
  caching	
  behavior	
  will	
  be	
  used.
@Cachable
@Entity

@Cacheable

public class Employee {

}
@Entity

@Cacheable(true)

public class Employee {

}
@Entity

@Cacheable(false)

public class Address {

}
44
@Cacheable
• @Cacheable	
  ignored	
  for	
  ALL	
  or	
  NONE
Cache	
  Retrieval	
  and	
  Store	
  
Modes
• Cache	
  Retrieval	
  Modes	
  
• javax.persistence.CacheRetrieveMode	
  
• USE	
  (default)	
  
• BYPASS	
  
• Cache	
  Store	
  Modes	
  
• javax.persistence.storeMode	
  
• USE	
  (default)	
  
• the	
  cache	
  data	
  is	
  created	
  or	
  updated	
  when	
  data	
  is	
  read	
  from	
  or	
  commiYed	
  to	
  
• when	
  data	
  is	
  already	
  in	
  the	
  cache,	
  no	
  refresh	
  on	
  read	
  
• REFRESH	
  
• forced	
  refresh	
  on	
  read	
  
• BYPASS
Cache	
  Retrieval	
  and	
  Store	
  
EntityManager em = ...;
em.setProperty("javax.persistence.cache.storeMode", “BYPASS");
Map<String, Object> props = new HashMap<String, Object>();
props.put("javax.persistence.cache.retrieveMode", "BYPASS");
Employee employee = = em.find(Employee.class, 1L, props);
TypedQuery<Employee> q = em.createQuery(cq);
q.setHint("javax.persistence.cache.storeMode", "REFRESH");
47
Programmatic	
  Access	
  to	
  Cache
EntityManager em = ...;
Cache cache = em.getEntityManagerFactory().getCache();
if (cache.contains(Employee.class, 1L)) {
// the data is cached
} else {
// the data is NOT cached
}
Cache interface methods:
boolean contains(Class cls, Object primaryKey)
void evict(Class cls)
void evict(Class cls, Object primaryKey)
void evictAll()
<T> T unwrap(Class<T> cls)
48
Forget	
  that!
• Don’t	
  use	
  cache	
  retrieval	
  and	
  store	
  modes	
  
• Don’t	
  use	
  programmaXc	
  access	
  to	
  2LC	
  
• Use	
  provider-­‐specific	
  configuraXon!
Hibernate	
  Caches
Hibernate	
  Caches
• First	
  Level	
  Cache	
  
• Second	
  Level	
  Cache	
  
• hydrated	
  or	
  disassembled	
  enXXes:	
  EnXtyEntry	
  
• collecXons	
  
• Query	
  Cache
Hibernate	
  Cache	
  ConfiguraXon
• hibernate.cache.use_second_level_cache	
  
• Enable	
  or	
  disable	
  second	
  level	
  caching	
  overall.	
  	
  
• Default	
  is	
  true	
  
• hibernate.cache.region.factory_class	
  
• Default	
  region	
  factory	
  is	
  NoCachingRegionFactory	
  
• hibernate.cache.use_query_cache	
  
• Enable	
  or	
  disable	
  second	
  level	
  caching	
  of	
  query	
  results.	
  	
  
• Default	
  is	
  false.	
  
• hibernate.cache.query_cache_factory
Hibernate	
  Cache	
  ConfiguraXon
• hibernate.cache.use_minimal_puts	
  
• OpXmizes	
  second-­‐level	
  cache	
  operaXons	
  to	
  minimize	
  writes,	
  at	
  the	
  
cost	
  of	
  more	
  frequent	
  reads.	
  Providers	
  typically	
  set	
  this	
  appropriately.	
  
• hibernate.cache.default_cache_concurrency_strategy	
  
• In	
  Hibernate	
  second-­‐level	
  caching,	
  all	
  regions	
  can	
  be	
  configured	
  
differently	
  including	
  the	
  concurrency	
  strategy	
  to	
  use	
  when	
  accessing	
  
that	
  parXcular	
  region.	
  This	
  sevng	
  allows	
  to	
  define	
  a	
  default	
  strategy	
  
to	
  be	
  used.	
  
• Providers	
  specify	
  this	
  sevng!
Hibernate	
  Cache	
  ConfiguraXon
• hibernate.cache.use_structured_entries	
  
• If	
  true,	
  forces	
  Hibernate	
  to	
  store	
  data	
  in	
  the	
  second-­‐level	
  cache	
  in	
  a	
  more	
  
human-­‐friendly	
  format.	
  	
  
• Default:	
  false	
  
• hibernate.cache.auto_evict_collecXon_cache	
  
• Enables	
  or	
  disables	
  the	
  automaXc	
  evicXon	
  of	
  a	
  bidirecXonal	
  associaXon’s	
  
collecXon	
  cache	
  entry	
  when	
  the	
  associaXon	
  is	
  changed	
  just	
  from	
  the	
  owning	
  
side.	
  
• Default:	
  false	
  
• hibernate.cache.use_reference_entries	
  
• Enable	
  direct	
  storage	
  of	
  enXty	
  references	
  into	
  the	
  second	
  level	
  cache	
  for	
  
read-­‐only	
  or	
  immutable	
  enXXes.
Cache	
  Concurrency	
  Strategy
• Global	
  cache	
  concurrency	
  strategy	
  
• hibernate.cache.default_cache_concurrency_strategy	
  
• Hibernate	
  @Cache	
  annotaXon	
  on	
  an	
  enXty	
  level	
  
• usage:	
  defines	
  the	
  CacheConcurrencyStrategy	
  
• region:	
  defines	
  a	
  cache	
  region	
  where	
  entries	
  will	
  be	
  stored	
  
• include:	
  if	
  lazy	
  properXes	
  should	
  be	
  included	
  in	
  the	
  second	
  level	
  
cache.	
  Default	
  value	
  is	
  "all",	
  so	
  lazy	
  properXes	
  are	
  cacheable.	
  The	
  
other	
  possible	
  value	
  is	
  "non-­‐lazy",	
  so	
  lazy	
  properXes	
  are	
  not	
  
cacheable.
Cache	
  Concurrency	
  Strategies
• read-­‐only	
  
• ApplicaXon	
  read-­‐only	
  data	
  
• Allows	
  deletes	
  
• read-­‐write	
  
• ApplicaXon	
  updates	
  data	
  
• Consistent	
  access	
  to	
  a	
  single	
  enXty,	
  but	
  not	
  a	
  serializable	
  transacXon	
  isolaXon	
  
level	
  
• nonstrict-­‐read-­‐write	
  
• Occasional	
  stale	
  reads	
  
• transacXonal	
  
• Provides	
  serializable	
  transacXon	
  isolaXon	
  level
Example	
  –	
  Entity	
  and	
  Collection	
  
Cache@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Employee {
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
@org.hibernate.annotations.Cache(usage =
CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Phone> phones = new HashSet<>();
}
// cache used!
Person person = entityManager.find(Employee.class, 1L);
// cache used!
Person person = entityManager.find(Employee.class, 1L);
person.getPhones().size();
57
Example	
  -­‐	
  Query	
  Cache
List<Employee> employees = entityManager.createQuery(
"select e " +
"from Employee e " +
"where e.firstName = :firstName", Employee.class)
.setParameter( "firstName", "John")
.setHint("org.hibernate.cacheable", "true")
.getResultList();
58
Puzzle	
  #2
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();

EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();

Employee employee = em2.find(Employee.class, 2L);

employee.getAddress().size();
em2.getTransaction().commit();

59
find,	
  no	
  collecXon	
  caching
Local DB
(ping: ~0.05ms)
North California
(ping: ~38ms)
EU Frankfurt
(ping: ~420ms)
No cache 87ms 186ms 1164ms
Cached 62ms 127ms 995ms
find,	
  collecXon	
  caching
Local DB
(ping: ~0.05ms)
North California
(ping: ~38ms)
EU Frankfurt
(ping: ~420ms)
No cache 82ms 162ms 1178ms
Cached 3ms 98ms 941ms
Puzzle	
  #2/P6Spy
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();

Employee employee = em1.find(Employee.class, 2L);

employee.getAddress().size();
em1.getTransaction().commit();

EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();

Employee employee = em2.find(Employee.class, 2L);

employee.getAddress().size();
em2.getTransaction().commit();

62
Available	
  Hibernate	
  2nd	
  Level	
  
Cache	
  ImplementaXons
• EHCache	
  
• Infinispan	
  
• Hazelcast
Infinispan	
  Configuration	
  (Local)
<!-- This configuration is suitable for non-clustered environments, where only single instance accesses the DB -->

<cache-container name="SampleCacheManager" statistics="false" default-cache="the-default-cache" shutdown-hook="DEFAULT">

<jmx duplicate-domains="true"/>



<local-cache-configuration name="the-default-cache" statistics="false" />



<!-- Default configuration is appropriate for entity/collection caching. -->

<local-cache-configuration name="entity" simple-cache="true" statistics="false" statistics-available="false">

<transaction mode="NONE" />

<eviction max-entries="10000" strategy="LRU"/>

<expiration max-idle="100000" interval="5000"/>

</local-cache-configuration>



<!-- A config appropriate for query caching. Does not replicate queries. -->

<local-cache-configuration name="local-query" simple-cache="true" statistics="false" statistics-available="false">

<transaction mode="NONE" />

<eviction max-entries="10000" strategy="LRU"/>

<expiration max-idle="100000" interval="5000"/>

</local-cache-configuration>



<local-cache-configuration name="timestamps" simple-cache="true" statistics="false" statistics-available="false">

<locking concurrency-level="1000" acquire-timeout="15000"/>

<!-- Explicitly non transactional -->

<transaction mode="NONE"/>

<!-- Don't ever evict modification timestamps -->

<eviction strategy="NONE"/>

<expiration interval="0"/>

</local-cache-configuration>



<!-- When providing custom configuration, always make this cache local and non-transactional.

64
Infinispan	
  Configuration	
  
(Clustered)<jgroups>

<stack-file name="hibernate-jgroups" path="${hibernate.cache.infinispan.jgroups_cfg:default-configs/default-jgroups-tcp.xml}"/>

</jgroups>

<cache-container name="SampleCacheManager" statistics="false" default-cache="the-default-cache" shutdown-hook="DEFAULT">

<transport stack="hibernate-jgroups" cluster="infinispan-hibernate-cluster"/>

<jmx duplicate-domains="true"/>



<local-cache-configuration name="the-default-cache" statistics="false" />



<!-- Default configuration is appropriate for entity/collection caching. -->

<invalidation-cache-configuration name="entity" mode="SYNC" remote-timeout="20000" statistics="false" statistics-available="false">

<locking concurrency-level="1000" acquire-timeout="15000"/>

<transaction mode="NONE" />

<eviction max-entries="10000" strategy="LRU"/>

<expiration max-idle="100000" interval="5000"/>

</invalidation-cache-configuration>



<!-- A config appropriate for query caching. Does not replicate queries. -->

<local-cache-configuration name="local-query" statistics="false" statistics-available="false">

<locking concurrency-level="1000" acquire-timeout="15000"/>

<transaction mode="NONE" />

<eviction max-entries="10000" strategy="LRU"/>

<expiration max-idle="100000" interval="5000"/>

</local-cache-configuration>



<!-- A query cache that replicates queries. Replication is asynchronous. -->

<replicated-cache-configuration name="replicated-query" mode="ASYNC" statistics="false" statistics-available="false">

<locking concurrency-level="1000" acquire-timeout="15000"/>

<transaction mode="NONE" />

<eviction max-entries="10000" strategy="LRU"/>

<expiration max-idle="100000" interval="5000"/>

</replicated-cache-configuration>



<!-- Optimized for timestamp caching. A clustered timestamp cache

is required if query caching is used, even if the query cache

itself is configured with CacheMode=LOCAL. -->

65
Guidelines
• Cache	
  as	
  much	
  as	
  you	
  can	
  
• As	
  much	
  RAM	
  you	
  have	
  
• Do	
  it	
  wisely	
  
• Read-­‐only	
  data	
  
• Almost	
  read-­‐only	
  data	
  
• More	
  reads	
  than	
  writes	
  
• Hit	
  raXo
EclipseLink
• 2LC	
  enabled	
  by	
  default	
  
• CollecXon	
  caching	
  
• Query	
  caching	
  
• @org.eclipse.persistence.annotaXons.Cache	
  
• type:	
  type	
  of	
  the	
  cache	
  (FULL,	
  WEAK,	
  SOFT,	
  SOFT_WEAK,	
  HARD_WEAK)	
  
• size:	
  number	
  of	
  objects	
  
• isolaXon:	
  shared,	
  isolated,	
  protected	
  
• expiry	
  
• expiryTimeOfDay	
  
• alwaysRefresh	
  
• refreshOnlyIfNewer	
  
• disableHits	
  
• coordinaXonType	
  
• databaseChangeNoXficaXonType
Conclusion
A	
  fool	
  with	
  a	
  tool	
  is	
  only	
  a	
  fool!
ConXnuous	
  Learning	
  
Please,	
  vote!	
  :)
Q&A
• patrycja@yonita.com	
  
• @yonlabs

More Related Content

What's hot

Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJSSandi Barr
 
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...Altinity Ltd
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1José Paumard
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfJosé Paumard
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introductionJonathan Holloway
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkMohit Kanwar
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceDatabricks
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013Vladimir Ivanov
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean ArchitectureMattia Battiston
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...Altinity Ltd
 

What's hot (20)

Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
JDBC
JDBCJDBC
JDBC
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
A Practical Introduction to Handling Log Data in ClickHouse, by Robert Hodges...
 
Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1Lambda and Stream Master class - part 1
Lambda and Stream Master class - part 1
 
From Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdfFrom Java 11 to 17 and beyond.pdf
From Java 11 to 17 and beyond.pdf
 
Jpa
JpaJpa
Jpa
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013JVM JIT-compiler overview @ JavaOne Moscow 2013
JVM JIT-compiler overview @ JavaOne Moscow 2013
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
 

Viewers also liked

Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Patrycja Wegrzynowicz
 
Java EE 6 & GlassFish 3
Java EE 6 & GlassFish 3Java EE 6 & GlassFish 3
Java EE 6 & GlassFish 3Arun Gupta
 
Performance Anti-Patterns in Hibernatee, by Patrycja Wegrzynowicz
Performance Anti-Patterns in Hibernatee, by Patrycja WegrzynowiczPerformance Anti-Patterns in Hibernatee, by Patrycja Wegrzynowicz
Performance Anti-Patterns in Hibernatee, by Patrycja WegrzynowiczCodemotion
 
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
 
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...Red Hat Developers
 
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
 

Viewers also liked (20)

Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Java EE 6 & GlassFish 3
Java EE 6 & GlassFish 3Java EE 6 & GlassFish 3
Java EE 6 & GlassFish 3
 
Performance Anti-Patterns in Hibernatee, by Patrycja Wegrzynowicz
Performance Anti-Patterns in Hibernatee, by Patrycja WegrzynowiczPerformance Anti-Patterns in Hibernatee, by Patrycja Wegrzynowicz
Performance Anti-Patterns in Hibernatee, by Patrycja Wegrzynowicz
 
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
 
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
 
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
How To Get The Most Out Of Your Hibernate, JBoss EAP 7 Application (Ståle Ped...
 
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
 
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
 

Similar to Second Level Cache in JPA Explained

Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
A Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQLA Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQLDatabricks
 
My Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sMy Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sRoel Hartman
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Testing and validating spark programs - Strata SJ 2016
Testing and validating spark programs - Strata SJ 2016Testing and validating spark programs - Strata SJ 2016
Testing and validating spark programs - Strata SJ 2016Holden Karau
 
Beyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden KarauBeyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden KarauSpark Summit
 
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...Databricks
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)William Farrell
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep DiveVasia Kalavri
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internalsKostas Tzoumas
 
Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0Lars Albertsson
 
Ufuc Celebi – Stream & Batch Processing in one System
Ufuc Celebi – Stream & Batch Processing in one SystemUfuc Celebi – Stream & Batch Processing in one System
Ufuc Celebi – Stream & Batch Processing in one SystemFlink Forward
 
The SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and ComputationThe SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and ComputationJean-Jacques Dubray
 
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
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamImre Nagi
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Holden Karau
 
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)Igalia
 

Similar to Second Level Cache in JPA Explained (20)

Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
A Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQLA Deep Dive into Query Execution Engine of Spark SQL
A Deep Dive into Query Execution Engine of Spark SQL
 
My Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API'sMy Top 5 APEX JavaScript API's
My Top 5 APEX JavaScript API's
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Flink internals web
Flink internals web Flink internals web
Flink internals web
 
Testing and validating spark programs - Strata SJ 2016
Testing and validating spark programs - Strata SJ 2016Testing and validating spark programs - Strata SJ 2016
Testing and validating spark programs - Strata SJ 2016
 
Beyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden KarauBeyond Parallelize and Collect by Holden Karau
Beyond Parallelize and Collect by Holden Karau
 
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
Everyday I'm Shuffling - Tips for Writing Better Spark Programs, Strata San J...
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep Dive
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internals
 
Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0Test strategies for data processing pipelines, v2.0
Test strategies for data processing pipelines, v2.0
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Ufuc Celebi – Stream & Batch Processing in one System
Ufuc Celebi – Stream & Batch Processing in one SystemUfuc Celebi – Stream & Batch Processing in one System
Ufuc Celebi – Stream & Batch Processing in one System
 
The SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and ComputationThe SAM Pattern: State Machines and Computation
The SAM Pattern: State Machines and Computation
 
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
 
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache BeamGDG Jakarta Meetup - Streaming Analytics With Apache Beam
GDG Jakarta Meetup - Streaming Analytics With Apache Beam
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
 
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
Standardizing JavaScript Decorators in TC39 (Full Stack Fest 2019)
 

More from Patrycja Wegrzynowicz

More from 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
 

Recently uploaded

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...SOFTTECHHUB
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)Samir Dash
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
الأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهالأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهMohamed Sweelam
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Navigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiNavigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiRaviKumarDaparthi
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
How to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in PakistanHow to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in Pakistandanishmna97
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxMasterG
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 

Recently uploaded (20)

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
الأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهالأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهله
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Navigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi DaparthiNavigating the Large Language Model choices_Ravi Daparthi
Navigating the Large Language Model choices_Ravi Daparthi
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
How to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in PakistanHow to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in Pakistan
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 

Second Level Cache in JPA Explained

  • 1. Second-­‐Level  Cache     in  JPA  Explained Patrycja  Wegrzynowicz   CTO,  Yonita,  Inc.   JavaOne  2016
  • 2. About  Me • 15+  professional  experience     • SoPware  engineer,  architect,  head  of   soPware  R&D     • Author  and  speaker     • JavaOne,  Devoxx,  JavaZone,   TheServerSide  Java  Symposium,  Jazoon,   OOPSLA,  ASE,  others     • Top  10  Women  in  Tech  2016  in  Poland   • Founder  and  CTO  of  Yonita   • Automated  detecXon  and  refactoring  of   soPware  defects   • Trainings  and  code  reviews   • Security,  performance,  concurrency,   databases     • TwiYer  @yonlabs  
  • 3. About  Me • 15+  professional  experience     • SoPware  engineer,  architect,  head  of   soPware  R&D     • Author  and  speaker     • JavaOne,  Devoxx,  JavaZone,   TheServerSide  Java  Symposium,  Jazoon,   OOPSLA,  ASE,  others     • Top  10  Women  in  Tech  2016  in  Poland   • Founder  and  CTO  of  Yonita   • Automated  detecXon  and  refactoring  of   soPware  defects   • Trainings  and  code  reviews   • Security,  performance,  concurrency,   databases     • TwiYer  @yonlabs  
  • 4. Agenda • Why  cacheing  is  important?   • 1st  Level  Cache  and  2nd  Level  Cache   • JPA  configuraXon  parameters  for  cache   • JPA  API  for  cache   • Hibernate  2nd  Level  Cache   • EclipseLink  2nd  Level  Cache  (a  bit)
  • 14. Employee  Entity @Entity public class Employee {
 @Id @GeneratedValue private Long id;
 private String firstName; 
 private String lastName;
 private BigDecimal salary;
 @OneToOne @JoinColumn(name = "address_id")
 private Address address;
 @Temporal(TemporalType.DATE)
 private Date startDate;
 @Temporal(TemporalType.DATE)
 private Date endDate; 
 @ManyToOne @JoinColumn(name = "manager_id")
 private Employee manager; // …
 } 14
  • 15. 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);
 }
 15
  • 16. 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);
 }
 16
  • 17. Sum  of  Salaries  by  Country
 Projection  (3) Query query = em.createQuery( "SELECT e.salary, e.address.country FROM Employee e");
 List<Object[]> list = (List<Object[]>) 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);
 }
 17
  • 18. Sum  of  Salaries  by  Country
 Aggregation  JPQL  (4) Query query = em.createQuery( "SELECT SUM(e.salary), e.address.country FROM Employee e GROUP BY e.address.country"); List<Object[]> list = (List<Object[]>) query.getResultList();
 // already calculated!
 18
  • 19. Comparison  1-­‐4  (Hibernate)   100000  Employees,  Different  DB  LocaXons Local DB (ping: ~0.05ms) North California (ping: ~38ms) EU Frankfurt (ping: ~420ms) (1) Select All (N+1) 26756ms 2-3 hours ~1 day (2) Select Join Fetch (3) Projection (4) Aggregation JPQL
  • 20. Comparison  1-­‐4   100000  Employees,  Different  DB  LocaXons Local DB (ping: ~0.05ms) North California (ping: ~38ms) EU Frankfurt (ping: ~420ms) (1) Select All (N+1) 26756ms 2-3 hours ~1 day (2) Select Join Fetch 4854ms 18027ms 25096ms (3) Projection (4) Aggregation JPQL
  • 21. Comparison  1-­‐4   100000  Employees,  Different  DB  LocaXons Local DB (ping: ~0.05ms) North California (ping: ~38ms) EU Frankfurt (ping: ~420ms) (1) Select All (N+1) 26756ms 2-3 hours ~1 day (2) Select Join Fetch 4854ms 18027ms 25096ms (3) Projection 653ms 2902ms 5006ms (4) Aggregation JPQL
  • 22. Comparison  1-­‐4   100000  Employees,  Different  DB  LocaXons Local DB (ping: ~0.05ms) North California (ping: ~38ms) EU Frankfurt (ping: ~420ms) (1) Select All (N+1) 26756ms 2-3 hours ~1 day (2) Select Join Fetch 4854ms 18027ms 25096ms (3) Projection 653ms 2902ms 5006ms (4) Aggregation JPQL 182ms 353ms 1198ms
  • 23. Performance  Tuning:  Data • Get  your  data  in  bigger  chunks     • Many  small  queries  =>  many  round-­‐trips  =>  huge  extra  Xme  on   transport  =>  high  latency   • Move  your  data  closer  to  the  processing  place   • Large  distance  to  data  =>  long  round-­‐trip  =>  high  latency   • Don’t  ask  about  the  same  data  many  Xmes   • Extra  processing  Xme  +  extra  transport  Xme Cache
  • 24. Cache  is  Everywhere Web Cache Application Cache RDBMS Cache DNS Cache OS Files Cache
  • 25. Second  Level  Cache  in   JPA
  • 26. JPA  Spec • “Persistence  providers  are  not  required  to  support  a   second-­‐level  cache.”   • “Portable  applicaXons  should  not  rely  on  support  by   persistence  providers  for  a  second-­‐level  cache.”
  • 27. JPA  Providers  Poll A. Hibernate   B. EclipseLink   C. OpenJPA   D. DataNuclues   E. Other
  • 28. • Second  Level  Cache   • Persistence  Unit   • EnXtyManagerFactory   • Thread-­‐safe,  shared   • Available  for  many  en1ty   managers  from  one  en1ty   manager  factory   • Provider  specific  support JPA  Caches • First  Level  Cache   • Persistence  Context   • EnXtyManager   • Not  thread-­‐safe   • Available  for  many   transac1ons  on  one  en1ty   manager   • Always
  • 30. Puzzle  #1 em.getTransaction().begin();
 Employee employee = em.find(Employee.class, 2L);
 employee.getAddress().size(); Employee another = em.find(Employee.class, 2L);
 em.getTransaction().commit();
 (A) No cache used (B) First Level Cache Used (C) Second Level Cache Used (D) None of the above 30
  • 31. Loading EntityManager Factory 2LC EntityManager 1LC load from 1LC load from 2LC select from database NOT FOUND NOT FOUND FOUND FOUND RESULT FIND
  • 32. Puzzle  #1 EntityManager em = emf.createEntityManager(); em.getTransaction().begin();
 Employee employee = em.find(Employee.class, 2L);
 employee.getAddress().size(); Employee another = em.find(Employee.class, 2L);
 em.getTransaction().commit();
 (A) No cache used (B) First Level Cache Used (C) Second Level Cache Used (D) None of the above 32
  • 33. Puzzle  #1 EntityManager em = emf.createEntityManager(); em.getTransaction().begin();
 Employee employee = em.find(Employee.class, 2L);
 employee.getAddress().size(); Employee another = em.find(Employee.class, 2L);
 em.getTransaction().commit();
 (A) No cache used (B) First Level Cache Used (C) Second Level Cache Used (D) None of the above 33
  • 34. Puzzle  #2 EntityManager em1 = emf.createEntityManager(); em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
 EntityManager em2 = emf.createEntityManager(); em2.getTransaction().begin();
 Employee employee = em2.find(Employee.class, 2L);
 employee.getAddress().size(); em2.getTransaction().commit();
 (A) No cache used (B) First Level Cache used (C) Second Level Cache used (D) None of the above 34
  • 35. Puzzle  #2 EntityManager em1 = emf.createEntityManager(); em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
 EntityManager em2 = emf.createEntityManager(); em2.getTransaction().begin();
 Employee employee = em2.find(Employee.class, 2L);
 employee.getAddress().size(); em2.getTransaction().commit();
 (A) No cache used (B) First Level Cache used (C) Second Level Cache used (D) None of the above 35
  • 36. Puzzle  #3  (2LC  Configured,   Hibernate) EntityManager em1 = emf.createEntityManager(); em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
 EntityManager em2 = emf.createEntityManager(); em2.getTransaction().begin();
 Employee employee = em2.find(Employee.class, 2L);
 employee.getAddress().size(); em2.getTransaction().commit();
 (A) No cache used (B) First Level Cache used (C) Second Level Cache used (D) None of the above 36
  • 37. Puzzle  #3  (2LC  Configured,   Hibernate) EntityManager em1 = emf.createEntityManager(); em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
 EntityManager em2 = emf.createEntityManager(); em2.getTransaction().begin();
 Employee employee = em2.find(Employee.class, 2L);
 employee.getAddress().size(); em2.getTransaction().commit();
 (A) No cache used (B) First Level Cache used (C) Second Level Cache used (D) None of the above 37
  • 38. Puzzle  #4  (2LC  Configured!) em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
a em2.getTransaction().begin();
 TypedQuery<Employee> q = em.createQuery("SELECT e FROM Employee e WHERE e.id=:id", Employee.class); q.setParameter("id", 2l);
 Employee employee = q.getSingleResult(); employee.getAddress().size(); em2.getTransaction().commit(); 
 (A) No cache used (B) First Level Cache used (C) Second Level Cache used (D) None of the above 38
  • 39. Puzzle  #4  (2LC  Configured!) em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
a em2.getTransaction().begin();
 TypedQuery<Employee> q = em.createQuery("SELECT e FROM Employee e WHERE e.id=:id", Employee.class); q.setParameter("id", 2l);
 Employee employee = q.getSingleResult(); employee.getAddress().size(); em2.getTransaction().commit(); 
 (A) No cache used (B) First Level Cache used (C) Second Level Cache used (D) None of the above 39
  • 41. Programmatic   Properties props = new Properties() .add(“javax.persistence.sharedCache.mode”, “ENABLE_SELECTIVE”); EntityManagerFactor emf = Persistence .createEntityManagerFactory(“test-pu”, props); 41
  • 42. JPA  Cache  Modes • ALL   • All  enXty  data  is  stored  in  the  second-­‐level  cache  for  this  persistence  unit.     • NONE     • No  data  is  cached  in  the  persistence  unit.  The  persistence  provider  must  not  cache  any   data.   • ENABLE_SELECTIVE     • Enable  caching  for  enXXes  that  have  been  explicitly  set  with  the  @Cacheable  annotaXon.   • DISABLE_SELECTIVE     • Enable  caching  for  all  enXXes  except  those  that  have  been  explicitly  set  with  the   @Cacheable(false)  annotaXon.     • UNSPECIFIED     • The  caching  behavior  for  the  persistence  unit  is  undefined.  The  persistence  provider’s   default  caching  behavior  will  be  used.
  • 43. JPA  Cache  Modes • ALL   • All  enXty  data  is  stored  in  the  second-­‐level  cache  for  this  persistence  unit.     • NONE     • No  data  is  cached  in  the  persistence  unit.  The  persistence  provider  must  not  cache  any   data.   • ENABLE_SELECTIVE     • Enable  caching  for  enXXes  that  have  been  explicitly  set  with  the  @Cacheable  annotaXon.   • DISABLE_SELECTIVE     • Enable  caching  for  all  enXXes  except  those  that  have  been  explicitly  set  with  the   @Cacheable(false)  annotaXon.     • UNSPECIFIED     • The  caching  behavior  for  the  persistence  unit  is  undefined.  The  persistence  provider’s   default  caching  behavior  will  be  used.
  • 44. @Cachable @Entity
 @Cacheable
 public class Employee {
 } @Entity
 @Cacheable(true)
 public class Employee {
 } @Entity
 @Cacheable(false)
 public class Address {
 } 44
  • 45. @Cacheable • @Cacheable  ignored  for  ALL  or  NONE
  • 46. Cache  Retrieval  and  Store   Modes • Cache  Retrieval  Modes   • javax.persistence.CacheRetrieveMode   • USE  (default)   • BYPASS   • Cache  Store  Modes   • javax.persistence.storeMode   • USE  (default)   • the  cache  data  is  created  or  updated  when  data  is  read  from  or  commiYed  to   • when  data  is  already  in  the  cache,  no  refresh  on  read   • REFRESH   • forced  refresh  on  read   • BYPASS
  • 47. Cache  Retrieval  and  Store   EntityManager em = ...; em.setProperty("javax.persistence.cache.storeMode", “BYPASS"); Map<String, Object> props = new HashMap<String, Object>(); props.put("javax.persistence.cache.retrieveMode", "BYPASS"); Employee employee = = em.find(Employee.class, 1L, props); TypedQuery<Employee> q = em.createQuery(cq); q.setHint("javax.persistence.cache.storeMode", "REFRESH"); 47
  • 48. Programmatic  Access  to  Cache EntityManager em = ...; Cache cache = em.getEntityManagerFactory().getCache(); if (cache.contains(Employee.class, 1L)) { // the data is cached } else { // the data is NOT cached } Cache interface methods: boolean contains(Class cls, Object primaryKey) void evict(Class cls) void evict(Class cls, Object primaryKey) void evictAll() <T> T unwrap(Class<T> cls) 48
  • 49. Forget  that! • Don’t  use  cache  retrieval  and  store  modes   • Don’t  use  programmaXc  access  to  2LC   • Use  provider-­‐specific  configuraXon!
  • 51. Hibernate  Caches • First  Level  Cache   • Second  Level  Cache   • hydrated  or  disassembled  enXXes:  EnXtyEntry   • collecXons   • Query  Cache
  • 52. Hibernate  Cache  ConfiguraXon • hibernate.cache.use_second_level_cache   • Enable  or  disable  second  level  caching  overall.     • Default  is  true   • hibernate.cache.region.factory_class   • Default  region  factory  is  NoCachingRegionFactory   • hibernate.cache.use_query_cache   • Enable  or  disable  second  level  caching  of  query  results.     • Default  is  false.   • hibernate.cache.query_cache_factory
  • 53. Hibernate  Cache  ConfiguraXon • hibernate.cache.use_minimal_puts   • OpXmizes  second-­‐level  cache  operaXons  to  minimize  writes,  at  the   cost  of  more  frequent  reads.  Providers  typically  set  this  appropriately.   • hibernate.cache.default_cache_concurrency_strategy   • In  Hibernate  second-­‐level  caching,  all  regions  can  be  configured   differently  including  the  concurrency  strategy  to  use  when  accessing   that  parXcular  region.  This  sevng  allows  to  define  a  default  strategy   to  be  used.   • Providers  specify  this  sevng!
  • 54. Hibernate  Cache  ConfiguraXon • hibernate.cache.use_structured_entries   • If  true,  forces  Hibernate  to  store  data  in  the  second-­‐level  cache  in  a  more   human-­‐friendly  format.     • Default:  false   • hibernate.cache.auto_evict_collecXon_cache   • Enables  or  disables  the  automaXc  evicXon  of  a  bidirecXonal  associaXon’s   collecXon  cache  entry  when  the  associaXon  is  changed  just  from  the  owning   side.   • Default:  false   • hibernate.cache.use_reference_entries   • Enable  direct  storage  of  enXty  references  into  the  second  level  cache  for   read-­‐only  or  immutable  enXXes.
  • 55. Cache  Concurrency  Strategy • Global  cache  concurrency  strategy   • hibernate.cache.default_cache_concurrency_strategy   • Hibernate  @Cache  annotaXon  on  an  enXty  level   • usage:  defines  the  CacheConcurrencyStrategy   • region:  defines  a  cache  region  where  entries  will  be  stored   • include:  if  lazy  properXes  should  be  included  in  the  second  level   cache.  Default  value  is  "all",  so  lazy  properXes  are  cacheable.  The   other  possible  value  is  "non-­‐lazy",  so  lazy  properXes  are  not   cacheable.
  • 56. Cache  Concurrency  Strategies • read-­‐only   • ApplicaXon  read-­‐only  data   • Allows  deletes   • read-­‐write   • ApplicaXon  updates  data   • Consistent  access  to  a  single  enXty,  but  not  a  serializable  transacXon  isolaXon   level   • nonstrict-­‐read-­‐write   • Occasional  stale  reads   • transacXonal   • Provides  serializable  transacXon  isolaXon  level
  • 57. Example  –  Entity  and  Collection   Cache@Entity @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Employee { @OneToMany(mappedBy = "employee", cascade = CascadeType.ALL) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set<Phone> phones = new HashSet<>(); } // cache used! Person person = entityManager.find(Employee.class, 1L); // cache used! Person person = entityManager.find(Employee.class, 1L); person.getPhones().size(); 57
  • 58. Example  -­‐  Query  Cache List<Employee> employees = entityManager.createQuery( "select e " + "from Employee e " + "where e.firstName = :firstName", Employee.class) .setParameter( "firstName", "John") .setHint("org.hibernate.cacheable", "true") .getResultList(); 58
  • 59. Puzzle  #2 EntityManager em1 = emf.createEntityManager(); em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
 EntityManager em2 = emf.createEntityManager(); em2.getTransaction().begin();
 Employee employee = em2.find(Employee.class, 2L);
 employee.getAddress().size(); em2.getTransaction().commit();
 59
  • 60. find,  no  collecXon  caching Local DB (ping: ~0.05ms) North California (ping: ~38ms) EU Frankfurt (ping: ~420ms) No cache 87ms 186ms 1164ms Cached 62ms 127ms 995ms
  • 61. find,  collecXon  caching Local DB (ping: ~0.05ms) North California (ping: ~38ms) EU Frankfurt (ping: ~420ms) No cache 82ms 162ms 1178ms Cached 3ms 98ms 941ms
  • 62. Puzzle  #2/P6Spy EntityManager em1 = emf.createEntityManager(); em1.getTransaction().begin();
 Employee employee = em1.find(Employee.class, 2L);
 employee.getAddress().size(); em1.getTransaction().commit();
 EntityManager em2 = emf.createEntityManager(); em2.getTransaction().begin();
 Employee employee = em2.find(Employee.class, 2L);
 employee.getAddress().size(); em2.getTransaction().commit();
 62
  • 63. Available  Hibernate  2nd  Level   Cache  ImplementaXons • EHCache   • Infinispan   • Hazelcast
  • 64. Infinispan  Configuration  (Local) <!-- This configuration is suitable for non-clustered environments, where only single instance accesses the DB -->
 <cache-container name="SampleCacheManager" statistics="false" default-cache="the-default-cache" shutdown-hook="DEFAULT">
 <jmx duplicate-domains="true"/>
 
 <local-cache-configuration name="the-default-cache" statistics="false" />
 
 <!-- Default configuration is appropriate for entity/collection caching. -->
 <local-cache-configuration name="entity" simple-cache="true" statistics="false" statistics-available="false">
 <transaction mode="NONE" />
 <eviction max-entries="10000" strategy="LRU"/>
 <expiration max-idle="100000" interval="5000"/>
 </local-cache-configuration>
 
 <!-- A config appropriate for query caching. Does not replicate queries. -->
 <local-cache-configuration name="local-query" simple-cache="true" statistics="false" statistics-available="false">
 <transaction mode="NONE" />
 <eviction max-entries="10000" strategy="LRU"/>
 <expiration max-idle="100000" interval="5000"/>
 </local-cache-configuration>
 
 <local-cache-configuration name="timestamps" simple-cache="true" statistics="false" statistics-available="false">
 <locking concurrency-level="1000" acquire-timeout="15000"/>
 <!-- Explicitly non transactional -->
 <transaction mode="NONE"/>
 <!-- Don't ever evict modification timestamps -->
 <eviction strategy="NONE"/>
 <expiration interval="0"/>
 </local-cache-configuration>
 
 <!-- When providing custom configuration, always make this cache local and non-transactional.
 64
  • 65. Infinispan  Configuration   (Clustered)<jgroups>
 <stack-file name="hibernate-jgroups" path="${hibernate.cache.infinispan.jgroups_cfg:default-configs/default-jgroups-tcp.xml}"/>
 </jgroups>
 <cache-container name="SampleCacheManager" statistics="false" default-cache="the-default-cache" shutdown-hook="DEFAULT">
 <transport stack="hibernate-jgroups" cluster="infinispan-hibernate-cluster"/>
 <jmx duplicate-domains="true"/>
 
 <local-cache-configuration name="the-default-cache" statistics="false" />
 
 <!-- Default configuration is appropriate for entity/collection caching. -->
 <invalidation-cache-configuration name="entity" mode="SYNC" remote-timeout="20000" statistics="false" statistics-available="false">
 <locking concurrency-level="1000" acquire-timeout="15000"/>
 <transaction mode="NONE" />
 <eviction max-entries="10000" strategy="LRU"/>
 <expiration max-idle="100000" interval="5000"/>
 </invalidation-cache-configuration>
 
 <!-- A config appropriate for query caching. Does not replicate queries. -->
 <local-cache-configuration name="local-query" statistics="false" statistics-available="false">
 <locking concurrency-level="1000" acquire-timeout="15000"/>
 <transaction mode="NONE" />
 <eviction max-entries="10000" strategy="LRU"/>
 <expiration max-idle="100000" interval="5000"/>
 </local-cache-configuration>
 
 <!-- A query cache that replicates queries. Replication is asynchronous. -->
 <replicated-cache-configuration name="replicated-query" mode="ASYNC" statistics="false" statistics-available="false">
 <locking concurrency-level="1000" acquire-timeout="15000"/>
 <transaction mode="NONE" />
 <eviction max-entries="10000" strategy="LRU"/>
 <expiration max-idle="100000" interval="5000"/>
 </replicated-cache-configuration>
 
 <!-- Optimized for timestamp caching. A clustered timestamp cache
 is required if query caching is used, even if the query cache
 itself is configured with CacheMode=LOCAL. -->
 65
  • 66. Guidelines • Cache  as  much  as  you  can   • As  much  RAM  you  have   • Do  it  wisely   • Read-­‐only  data   • Almost  read-­‐only  data   • More  reads  than  writes   • Hit  raXo
  • 67. EclipseLink • 2LC  enabled  by  default   • CollecXon  caching   • Query  caching   • @org.eclipse.persistence.annotaXons.Cache   • type:  type  of  the  cache  (FULL,  WEAK,  SOFT,  SOFT_WEAK,  HARD_WEAK)   • size:  number  of  objects   • isolaXon:  shared,  isolated,  protected   • expiry   • expiryTimeOfDay   • alwaysRefresh   • refreshOnlyIfNewer   • disableHits   • coordinaXonType   • databaseChangeNoXficaXonType
  • 69. A  fool  with  a  tool  is  only  a  fool!