SlideShare a Scribd company logo
<Insert Picture Here>




Using the Latest Java Persistence API 2.0 Features
Arun Gupta, Java EE & GlassFish Guy
blogs.sun.com/arungupta, @arungupta
Java Persistence API
 Object/Relational Mapping for Java Developers

• The standard API for object/relational persistence for
  Java SE and Java EE applications
• Automatic mapping from Java object domain model to
  relational database
• Mapping is explicit, not “magic”
  • Uses annotations and/or XML
  • Many useful defaults
  • Lots of hooks and options for customization
• SQL-like query language (JPQL)
   • Applied to domain model
   • Supports both static and dynamic queries


                                                           2
Background

• JPA 1.0
 • Introduced as part of Java EE 5; also available
   standalone
    • Part of the EJB 3.0 simplification effort
 • Based on experience with existing technology:
    • TopLink, Hibernate, JDO
 • Covered all the essentials++




                                                     3
JPA 2.0 (JSR 317)

• JPA 2.0
 • Part of Java EE 6 and/or available standalone
 • Adds more sophisticated mapping and modeling
   options
 • Expanded query language
 • Adds Criteria API, together with Metamodel API
 • Support for Validation
 • EclipseLink is reference implementation
 • Integrated in GlassFish




                                                    4
Object/Relational Mapping
 Essentials

• Entities
• Basic types
   • Strings, integers, floats, decimals, …
• Embeddable classes
   • E.g., Address
• Relationships
   • One-to-one, one-to-many/many-to-one, many-to-many
   • Collections modeled with java.util Collection, Set, List, or Map
   • Customized via metadata: @JoinColumn, @JoinTable, etc.
• Inheritance
   • Single table, joined subclass, table per class (optional)


                                                                        5
Object/Relational Mapping
 New in JPA 2.0

• Element collections
   • Collections of strings, integers, floats, decimals, …
   • Collections of embeddable classes
• Embeddable classes
   • Nested embeddables; embeddables with relationships
• Persistently ordered lists
• Improved Map support
• More relationship mapping options
  • Unidirectional one-many foreign key mappings
  • Join table mappings for one-one, one-many/many-one



                                                             6
Collections of Basic Types

@Entity
public class Person {
    @Id protected String ssn;
    protected String name;
    protected Date birthDate;
    . . .
    @ElementCollection
    protected Set<String> nickNames;
}




                                       7
Collections of Basic Types

@Entity
public class Person {
    @Id protected String ssn;
    protected String name;
    protected Date birthDate;
    . . .
    @ElementCollection
    @CollectionTable(name=”ALIAS”)
    protected Set<String> nickNames;
}




                                       8
Collection of Embeddable Types

@Embeddable public class Address {
    String street;
    String city;
    String state;
    . . .
}

@Entity public class RichPerson extends Person {
    . . .
    @ElementCollection
    protected Set<Address> vacationHomes;
    . . .
}



                                                   9
Multiple Levels of Embedding

@Embeddable public class ContactInfo {
    @Embedded Address address;
    . . .
}


@Entity public class Employee {
    @Id int empId;
    String name;
    ContactInfo contactInfo;
    . . .
}




                                         10
Embeddables with Relationships

@Embeddable public class ContactInfo {
    @Embedded Address address;
    @OneToMany Set<Phone> phones;
    . . .
}


@Entity public class Employee {
    @Id int empId;
    String name;
    ContactInfo contactInfo;
    . . .
}




                                         11
Ordered Lists

@Entity public class CreditCard {
    @Id long cardNumber;
    @OneToOne Person cardHolder;
    . . .
    @OneToMany
    @OrderColumn
    List<CardTransaction> transactions;
}




                                          12
Maps

@Entity public class VideoStore {
    @Id Integer storeId;
    Address location;
    . . .
    @ElementCollection
    Map<Movie, Integer> inventory;
}

@Entity public class Movie {
    @Id String title;
    @String director;
    . . .
}



                                     13
Automatic Orphan Deletion

For entities logically “owned” by “parent”

@Entity public class Order {
    @Id int orderId;
    . . .
    @OneToMany(cascade=PERSIST, orphanRemoval=true)
    Set<Item> lineItems;
    . . .
}




                                                      14
Key Interfaces

• EntityManagerFactory
   • Used to create entity managers
   • One entity manager factory per persistence unit
• EntityManager
   • Used to manage persistence context
      • Entities read/written from database
   • Operations: persist, remove, find, refresh, createQuery,…
• Query, TypedQuery
  • Used for query configuration, parameter binding, query
    execution




                                                                 15
Java Persistence Query Language

• String-based SQL-like query language
   • SELECT, FROM, WHERE, GROUP BY, ORDER BY,…
• Queries written over Java domain model
  • Entities, state, relationships
  • Supports navigation using dot-notation
  • Mapped into SQL by the provider
• Supports static and dynamic use

SELECT AVG (p.price)
FROM Order o JOIN o.products p
WHERE o.customer.address.zip = ‘94301’



                                                 16
Java Persistence Query Language
 New in JPA 2.0

• Support for all new modeling and mapping features
• Operators and functions in select list
• Case, coalesce, nullif expressions
• Restricted polymorphism
• Collection-valued parameters for IN-expressions




                                                      17
JPQL New Operators

INDEX
  For ordered Lists
KEY, VALUE, ENTRY
  For maps
CASE, COALESCE, NULLIF
  For case expressions, etc.
TYPE
  For restricted polymorphism



                                18
Ordered Lists

SELECT t
FROM CreditCard c JOIN c.transactions t
WHERE c.cardHolder.name = 'John Doe'
  AND INDEX(t) < 10




                                          19
Maps

// Inventory is Map<Movie, Integer>

SELECT v.location.street, KEY(i).title, VALUE(i),
FROM VideoStore v JOIN v.inventory i
WHERE KEY(i).director LIKE '%Hitchcock%'
  AND VALUE(i) > 0




                                                    20
Case Expressions

UPDATE Employee e
SET e.salary =
  CASE e.rating
    WHEN 1 THEN e.salary * 1.05
    WHEN 2 THEN e.salary * 1.02
    ELSE e.salary * 0.95
  END




                                  21
Restricted Polymorphism

SELECT e
FROM Employee e
WHERE TYPE(e) IN :empTypes




                             22
Criteria API
 New in JPA 2.0

• Object-based API for building queries
• Designed to mirror JPQL semantics
• Strongly typed
   • Based on type-safe metamodel of persistent classes and
     relationships
   • Heavy use of Java generics
   • Supports object-based or string-based navigation
• Query construction at development time or runtime




                                                              23
Criteria API: Core Interfaces

• CriteriaBuilder
   • Used to construct criteria queries, selections, predicates, orderings
• CriteriaQuery
   • Used to add / replace/ browse query elements
   • from, select, where, orderBy, groupBy, having,… methods
• Root
   • Query roots
• Join, ListJoin, MapJoin, …
   • Joins from a root or existing join
• Path
   • Navigation from a root, join, or path
• Subquery



                                                                             24
How to Build a Criteria Query

EntityManager em = …;
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ResultType> cquery =
    cb.createQuery(ResultType.class);
Root<MyEntity> e = cquery.from(MyEntity.class);
Join<MyEntity, RelatedEntity> j = e.join(…);
…
cquery.select(…)
      .where(…)
      .orderBy(…)
      .groupBy(…);

TypedQuery<ResultType> tq = em.createQuery(cquery);
List<ResultType> result = tq.getResultList();


                                                      25
Validation
 New in JPA 2.0

• Leverages work of Bean Validation (JSR 303)
• Automatic validation upon lifecycle events
   • PrePersist
   • PreUpdate
   • PreRemove
• Validation-mode element in “persistence.xml”
   • AUTO, CALLBACK, NONE
• Standardization of many configuration options




                                                  26
Sample Database

            Card TX                       Supplier


                               Product
Customer   CreditCard
                               Supplier
             Phone

            Orders             Product



                        Book    DVD          CD

                                                     27
Metamodel

• Abstract “schema-level” view of managed classes
   • Entities, mapped superclasses, embeddables
• Accessed dynamically
   • EntityManagerFactory.getMetamodel()
   • EntityManager.getMetamodel()
• And/or materialized as static metamodel classes
   • Used to create strongly-typed criteria queries
   • Spec defines canonical format




                                                      28
Generating Static Metamodel

javac -processor
org.eclipse.persistence.internal.jpa.modelgen.CanonicalM
odelProcessor -sourcepath src -d src -classpath
/ace2_apps/eclipselink/jlib/eclipselink.jar:.:/ace2_apps
/eclipselink/jlib/JPA/javax.persistence_2.0.0.v200911271
158.jar -proc:only
-Aeclipselink.persistencexml=src/META-
INF/persistence.xml src/demo/*.java
Note: Creating the metadata factory …
Note: Building metadata class for round element:
demo.Item
. . .

http://weblogs.java.net/blog/lancea/archive/2009/12/15/generating-jpa-20-static-metamodel-classes-using-eclipselink-20-and-n




                                                                                                                               29
Entity Class
package com.example;

import   javax.persistence.Entity;
import   javax.persistence.Id;
import   javax.persistence.Embedded;
import   javax.persistence.OneToMany;
import   java.util.Set;

@Entity
public class Customer {
  @Id int custId;
  @Embedded Address address;
  @OneToMany Set<Order> orders;
  …
}


                                        30
Metamodel Class
package com.example;


import   javax.annotation.Generated;
import   javax.persistence.metamodel.SetAttribute;
import   javax.persistence.metamodel.SingularAttribute;
import   javax.persistence.metamodel.StaticMetamodel;


@Generated(“EclipseLink JPA 2.0 Canonical Model Generation”)
@StaticMetamodel(Customer.class)
public class Customer_ {
  public static volatile SingularAttribute<Customer,Integer> custId;
  public static volatile SingularAttribute<Customer,Address>
address;
  public static volatile SetAttribute<Customer,Order> orders;
  …
}




                                                                  31
Concurrency

• Java Persistence assumes optimistic concurrency
   • Short-term read locks
   • Long-term write locks
   • Provider can defer writing to database to transaction commit
   • Application can flush to database on demand
• Optimistic “locking” done via version attributes
  • Integral or timestamp attributes, managed by provider
  • Provider validates version when writing to database
  • Explicit lock() calls available to validate read data




                                                                    32
Pessimistic Locking
 New in JPA 2.0

• Java Persistence assumes optimistic concurrency
   • Normal pessimistic locking
   • Persistent state of entity
      • Relationships, Element collections
• Grab database locks upfront
  • JPA spec defines semantics, not mechanism
  • Provider can lock more (not less)
• Lock modes
   • PESSIMISTIC_READ – grab shared lock
   • PESSIMISTIC_WRITE – grab exclusive lock
   • PESSIMISTIC_FORCE_INCREMENT – update version


                                                    33
Locking APIs

• EntityManager methods: lock, find, refresh
• Query / TypedQuery methods: setLockMode, setHint
• NamedQuery annotation: lockMode element


• javax.persistence.lock.scope property
• javax.persistence.lock.timeout hint


• PessimisticLockException (if transaction rolls back)
• LockTimeoutException (if only statement rolls back)



                                                         34
Caching Configuration
 New in JPA 2.0

• EntityManager persistence context corresponds to
 “first level” cache
  • Entities managed by persistence provider
     • Entities read from database
     • Entities to be written to database
• Most implementations also use second-level caches
  • Not always transparent to application
• JPA 2.0 standardizes basic second-level cache
 options




                                                      35
Standard Configuration Properties

• javax.persistence.jdbc.driver
• javax.persistence.jdbc.url
• javax.persistence.jdbc.user
• javax.persistence.jdbc.password
• ...




                                     36
Summary of JPA 2.0 New Features

• More flexible modeling capabilities
• Expanded O/R mapping functionality
• Additions to Java Persistence query language
• Criteria API
• Metamodel API
• Pessimistic locking
• Support for validation
• Standardization of many configuration options




                                                  37
<Insert Picture Here>




Using the Latest Java Persistence API 2.0 Features
Arun Gupta, Java EE & GlassFish Guy
blogs.sun.com/arungupta, @arungupta

More Related Content

What's hot

Effectively Testing Services - Burlington Ruby Conf
Effectively Testing Services - Burlington Ruby ConfEffectively Testing Services - Burlington Ruby Conf
Effectively Testing Services - Burlington Ruby Conf
neal_kemp
 
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIOJumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
Josh Cypher
 
Practices and tools for building better API (JFall 2013)
Practices and tools for building better API (JFall 2013)Practices and tools for building better API (JFall 2013)
Practices and tools for building better API (JFall 2013)
Peter Hendriks
 
Introduction to Apigility
Introduction to ApigilityIntroduction to Apigility
Introduction to Apigility
Engineor
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to concepts
Abhishek Sur
 
Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)
Engineor
 
REST full API Design
REST full API DesignREST full API Design
REST full API Design
Christian Guenther
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
Darwin Biler
 
Current Testing Challenges Ireland
Current Testing Challenges IrelandCurrent Testing Challenges Ireland
Current Testing Challenges IrelandDavid O'Dowd
 
Api testing
Api testingApi testing
Api testing
Keshav Kashyap
 
2010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week12010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week1
Wolfram Arnold
 
iOS development best practices
iOS development best practicesiOS development best practices
iOS development best practices
Michal Juhas
 
Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014
OSSCube
 
Bdd with Cucumber and Mocha
Bdd with Cucumber and MochaBdd with Cucumber and Mocha
Bdd with Cucumber and Mocha
Atish Narlawar
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberKMS Technology
 
Publishing strategies for API documentation
Publishing strategies for API documentationPublishing strategies for API documentation
Publishing strategies for API documentation
Tom Johnson
 
Bdd – with cucumber and gherkin
Bdd – with cucumber and gherkinBdd – with cucumber and gherkin
Bdd – with cucumber and gherkin
Arati Joshi
 

What's hot (17)

Effectively Testing Services - Burlington Ruby Conf
Effectively Testing Services - Burlington Ruby ConfEffectively Testing Services - Burlington Ruby Conf
Effectively Testing Services - Burlington Ruby Conf
 
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIOJumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
Jumpstarting Testing In Your Organization with Selenium, Cucumber, & WebdriverIO
 
Practices and tools for building better API (JFall 2013)
Practices and tools for building better API (JFall 2013)Practices and tools for building better API (JFall 2013)
Practices and tools for building better API (JFall 2013)
 
Introduction to Apigility
Introduction to ApigilityIntroduction to Apigility
Introduction to Apigility
 
Angular JS, A dive to concepts
Angular JS, A dive to conceptsAngular JS, A dive to concepts
Angular JS, A dive to concepts
 
Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)Apigility introduction v2 (glasgow php)
Apigility introduction v2 (glasgow php)
 
REST full API Design
REST full API DesignREST full API Design
REST full API Design
 
Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
 
Current Testing Challenges Ireland
Current Testing Challenges IrelandCurrent Testing Challenges Ireland
Current Testing Challenges Ireland
 
Api testing
Api testingApi testing
Api testing
 
2010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week12010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week1
 
iOS development best practices
iOS development best practicesiOS development best practices
iOS development best practices
 
Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014 Apigility – Lightning Fast API Development - OSSCamp 2014
Apigility – Lightning Fast API Development - OSSCamp 2014
 
Bdd with Cucumber and Mocha
Bdd with Cucumber and MochaBdd with Cucumber and Mocha
Bdd with Cucumber and Mocha
 
Behavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using CucumberBehavior Driven Development and Automation Testing Using Cucumber
Behavior Driven Development and Automation Testing Using Cucumber
 
Publishing strategies for API documentation
Publishing strategies for API documentationPublishing strategies for API documentation
Publishing strategies for API documentation
 
Bdd – with cucumber and gherkin
Bdd – with cucumber and gherkinBdd – with cucumber and gherkin
Bdd – with cucumber and gherkin
 

Similar to Using the latest Java Persistence API 2 Features - Tech Days 2010 India

Using the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresUsing the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresArun Gupta
 
Understanding
Understanding Understanding
Understanding Arun Gupta
 
S313431 JPA 2.0 Overview
S313431 JPA 2.0 OverviewS313431 JPA 2.0 Overview
S313431 JPA 2.0 Overview
Ludovic Champenois
 
Java Persistence API 2.0: An Overview
Java Persistence API 2.0: An OverviewJava Persistence API 2.0: An Overview
Java Persistence API 2.0: An Overview
Sanjeeb Sahoo
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
Sunghyouk Bae
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
NAVER Engineering
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
ssuser0562f1
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
Markus Eisele
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
Software Park Thailand
 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Baruch Sadogursky
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
Gaej For Beginners
Gaej For BeginnersGaej For Beginners
Gaej For Beginners
Shinichi Ogawa
 
Requery overview
Requery overviewRequery overview
Requery overview
Sunghyouk Bae
 
ORM JPA
ORM JPAORM JPA
Learning to run
Learning to runLearning to run
Learning to run
dominion
 

Similar to Using the latest Java Persistence API 2 Features - Tech Days 2010 India (20)

Using the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresUsing the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 features
 
Understanding
Understanding Understanding
Understanding
 
S313431 JPA 2.0 Overview
S313431 JPA 2.0 OverviewS313431 JPA 2.0 Overview
S313431 JPA 2.0 Overview
 
Java Persistence API 2.0: An Overview
Java Persistence API 2.0: An OverviewJava Persistence API 2.0: An Overview
Java Persistence API 2.0: An Overview
 
Jpa
JpaJpa
Jpa
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Gaej For Beginners
Gaej For BeginnersGaej For Beginners
Gaej For Beginners
 
Requery overview
Requery overviewRequery overview
Requery overview
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Learning to run
Learning to runLearning to run
Learning to run
 

More from Arun Gupta

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf
Arun Gupta
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019
Arun Gupta
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesMachine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and Kubernetes
Arun Gupta
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerSecure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using Firecracker
Arun Gupta
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019
Arun Gupta
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open SourceWhy Amazon Cares about Open Source
Why Amazon Cares about Open Source
Arun Gupta
 
Machine learning using Kubernetes
Machine learning using KubernetesMachine learning using Kubernetes
Machine learning using Kubernetes
Arun Gupta
 
Building Cloud Native Applications
Building Cloud Native ApplicationsBuilding Cloud Native Applications
Building Cloud Native Applications
Arun Gupta
 
Chaos Engineering with Kubernetes
Chaos Engineering with KubernetesChaos Engineering with Kubernetes
Chaos Engineering with Kubernetes
Arun Gupta
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMHow to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAM
Arun Gupta
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018
Arun Gupta
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteThe Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 Keynote
Arun Gupta
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018
Arun Gupta
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitMastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv Summit
Arun Gupta
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeTop 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's Landscape
Arun Gupta
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017
Arun Gupta
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftJava EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Arun Gupta
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersDocker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developers
Arun Gupta
 
Thanks Managers!
Thanks Managers!Thanks Managers!
Thanks Managers!
Arun Gupta
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersMigrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to Containers
Arun Gupta
 

More from Arun Gupta (20)

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesMachine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and Kubernetes
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerSecure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using Firecracker
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open SourceWhy Amazon Cares about Open Source
Why Amazon Cares about Open Source
 
Machine learning using Kubernetes
Machine learning using KubernetesMachine learning using Kubernetes
Machine learning using Kubernetes
 
Building Cloud Native Applications
Building Cloud Native ApplicationsBuilding Cloud Native Applications
Building Cloud Native Applications
 
Chaos Engineering with Kubernetes
Chaos Engineering with KubernetesChaos Engineering with Kubernetes
Chaos Engineering with Kubernetes
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMHow to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAM
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteThe Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 Keynote
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitMastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv Summit
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeTop 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's Landscape
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftJava EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShift
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersDocker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developers
 
Thanks Managers!
Thanks Managers!Thanks Managers!
Thanks Managers!
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersMigrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to Containers
 

Recently uploaded

zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

Using the latest Java Persistence API 2 Features - Tech Days 2010 India

  • 1. <Insert Picture Here> Using the Latest Java Persistence API 2.0 Features Arun Gupta, Java EE & GlassFish Guy blogs.sun.com/arungupta, @arungupta
  • 2. Java Persistence API Object/Relational Mapping for Java Developers • The standard API for object/relational persistence for Java SE and Java EE applications • Automatic mapping from Java object domain model to relational database • Mapping is explicit, not “magic” • Uses annotations and/or XML • Many useful defaults • Lots of hooks and options for customization • SQL-like query language (JPQL) • Applied to domain model • Supports both static and dynamic queries 2
  • 3. Background • JPA 1.0 • Introduced as part of Java EE 5; also available standalone • Part of the EJB 3.0 simplification effort • Based on experience with existing technology: • TopLink, Hibernate, JDO • Covered all the essentials++ 3
  • 4. JPA 2.0 (JSR 317) • JPA 2.0 • Part of Java EE 6 and/or available standalone • Adds more sophisticated mapping and modeling options • Expanded query language • Adds Criteria API, together with Metamodel API • Support for Validation • EclipseLink is reference implementation • Integrated in GlassFish 4
  • 5. Object/Relational Mapping Essentials • Entities • Basic types • Strings, integers, floats, decimals, … • Embeddable classes • E.g., Address • Relationships • One-to-one, one-to-many/many-to-one, many-to-many • Collections modeled with java.util Collection, Set, List, or Map • Customized via metadata: @JoinColumn, @JoinTable, etc. • Inheritance • Single table, joined subclass, table per class (optional) 5
  • 6. Object/Relational Mapping New in JPA 2.0 • Element collections • Collections of strings, integers, floats, decimals, … • Collections of embeddable classes • Embeddable classes • Nested embeddables; embeddables with relationships • Persistently ordered lists • Improved Map support • More relationship mapping options • Unidirectional one-many foreign key mappings • Join table mappings for one-one, one-many/many-one 6
  • 7. Collections of Basic Types @Entity public class Person { @Id protected String ssn; protected String name; protected Date birthDate; . . . @ElementCollection protected Set<String> nickNames; } 7
  • 8. Collections of Basic Types @Entity public class Person { @Id protected String ssn; protected String name; protected Date birthDate; . . . @ElementCollection @CollectionTable(name=”ALIAS”) protected Set<String> nickNames; } 8
  • 9. Collection of Embeddable Types @Embeddable public class Address { String street; String city; String state; . . . } @Entity public class RichPerson extends Person { . . . @ElementCollection protected Set<Address> vacationHomes; . . . } 9
  • 10. Multiple Levels of Embedding @Embeddable public class ContactInfo { @Embedded Address address; . . . } @Entity public class Employee { @Id int empId; String name; ContactInfo contactInfo; . . . } 10
  • 11. Embeddables with Relationships @Embeddable public class ContactInfo { @Embedded Address address; @OneToMany Set<Phone> phones; . . . } @Entity public class Employee { @Id int empId; String name; ContactInfo contactInfo; . . . } 11
  • 12. Ordered Lists @Entity public class CreditCard { @Id long cardNumber; @OneToOne Person cardHolder; . . . @OneToMany @OrderColumn List<CardTransaction> transactions; } 12
  • 13. Maps @Entity public class VideoStore { @Id Integer storeId; Address location; . . . @ElementCollection Map<Movie, Integer> inventory; } @Entity public class Movie { @Id String title; @String director; . . . } 13
  • 14. Automatic Orphan Deletion For entities logically “owned” by “parent” @Entity public class Order { @Id int orderId; . . . @OneToMany(cascade=PERSIST, orphanRemoval=true) Set<Item> lineItems; . . . } 14
  • 15. Key Interfaces • EntityManagerFactory • Used to create entity managers • One entity manager factory per persistence unit • EntityManager • Used to manage persistence context • Entities read/written from database • Operations: persist, remove, find, refresh, createQuery,… • Query, TypedQuery • Used for query configuration, parameter binding, query execution 15
  • 16. Java Persistence Query Language • String-based SQL-like query language • SELECT, FROM, WHERE, GROUP BY, ORDER BY,… • Queries written over Java domain model • Entities, state, relationships • Supports navigation using dot-notation • Mapped into SQL by the provider • Supports static and dynamic use SELECT AVG (p.price) FROM Order o JOIN o.products p WHERE o.customer.address.zip = ‘94301’ 16
  • 17. Java Persistence Query Language New in JPA 2.0 • Support for all new modeling and mapping features • Operators and functions in select list • Case, coalesce, nullif expressions • Restricted polymorphism • Collection-valued parameters for IN-expressions 17
  • 18. JPQL New Operators INDEX For ordered Lists KEY, VALUE, ENTRY For maps CASE, COALESCE, NULLIF For case expressions, etc. TYPE For restricted polymorphism 18
  • 19. Ordered Lists SELECT t FROM CreditCard c JOIN c.transactions t WHERE c.cardHolder.name = 'John Doe' AND INDEX(t) < 10 19
  • 20. Maps // Inventory is Map<Movie, Integer> SELECT v.location.street, KEY(i).title, VALUE(i), FROM VideoStore v JOIN v.inventory i WHERE KEY(i).director LIKE '%Hitchcock%' AND VALUE(i) > 0 20
  • 21. Case Expressions UPDATE Employee e SET e.salary = CASE e.rating WHEN 1 THEN e.salary * 1.05 WHEN 2 THEN e.salary * 1.02 ELSE e.salary * 0.95 END 21
  • 22. Restricted Polymorphism SELECT e FROM Employee e WHERE TYPE(e) IN :empTypes 22
  • 23. Criteria API New in JPA 2.0 • Object-based API for building queries • Designed to mirror JPQL semantics • Strongly typed • Based on type-safe metamodel of persistent classes and relationships • Heavy use of Java generics • Supports object-based or string-based navigation • Query construction at development time or runtime 23
  • 24. Criteria API: Core Interfaces • CriteriaBuilder • Used to construct criteria queries, selections, predicates, orderings • CriteriaQuery • Used to add / replace/ browse query elements • from, select, where, orderBy, groupBy, having,… methods • Root • Query roots • Join, ListJoin, MapJoin, … • Joins from a root or existing join • Path • Navigation from a root, join, or path • Subquery 24
  • 25. How to Build a Criteria Query EntityManager em = …; CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ResultType> cquery = cb.createQuery(ResultType.class); Root<MyEntity> e = cquery.from(MyEntity.class); Join<MyEntity, RelatedEntity> j = e.join(…); … cquery.select(…) .where(…) .orderBy(…) .groupBy(…); TypedQuery<ResultType> tq = em.createQuery(cquery); List<ResultType> result = tq.getResultList(); 25
  • 26. Validation New in JPA 2.0 • Leverages work of Bean Validation (JSR 303) • Automatic validation upon lifecycle events • PrePersist • PreUpdate • PreRemove • Validation-mode element in “persistence.xml” • AUTO, CALLBACK, NONE • Standardization of many configuration options 26
  • 27. Sample Database Card TX Supplier Product Customer CreditCard Supplier Phone Orders Product Book DVD CD 27
  • 28. Metamodel • Abstract “schema-level” view of managed classes • Entities, mapped superclasses, embeddables • Accessed dynamically • EntityManagerFactory.getMetamodel() • EntityManager.getMetamodel() • And/or materialized as static metamodel classes • Used to create strongly-typed criteria queries • Spec defines canonical format 28
  • 29. Generating Static Metamodel javac -processor org.eclipse.persistence.internal.jpa.modelgen.CanonicalM odelProcessor -sourcepath src -d src -classpath /ace2_apps/eclipselink/jlib/eclipselink.jar:.:/ace2_apps /eclipselink/jlib/JPA/javax.persistence_2.0.0.v200911271 158.jar -proc:only -Aeclipselink.persistencexml=src/META- INF/persistence.xml src/demo/*.java Note: Creating the metadata factory … Note: Building metadata class for round element: demo.Item . . . http://weblogs.java.net/blog/lancea/archive/2009/12/15/generating-jpa-20-static-metamodel-classes-using-eclipselink-20-and-n 29
  • 30. Entity Class package com.example; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Embedded; import javax.persistence.OneToMany; import java.util.Set; @Entity public class Customer { @Id int custId; @Embedded Address address; @OneToMany Set<Order> orders; … } 30
  • 31. Metamodel Class package com.example; import javax.annotation.Generated; import javax.persistence.metamodel.SetAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(“EclipseLink JPA 2.0 Canonical Model Generation”) @StaticMetamodel(Customer.class) public class Customer_ { public static volatile SingularAttribute<Customer,Integer> custId; public static volatile SingularAttribute<Customer,Address> address; public static volatile SetAttribute<Customer,Order> orders; … } 31
  • 32. Concurrency • Java Persistence assumes optimistic concurrency • Short-term read locks • Long-term write locks • Provider can defer writing to database to transaction commit • Application can flush to database on demand • Optimistic “locking” done via version attributes • Integral or timestamp attributes, managed by provider • Provider validates version when writing to database • Explicit lock() calls available to validate read data 32
  • 33. Pessimistic Locking New in JPA 2.0 • Java Persistence assumes optimistic concurrency • Normal pessimistic locking • Persistent state of entity • Relationships, Element collections • Grab database locks upfront • JPA spec defines semantics, not mechanism • Provider can lock more (not less) • Lock modes • PESSIMISTIC_READ – grab shared lock • PESSIMISTIC_WRITE – grab exclusive lock • PESSIMISTIC_FORCE_INCREMENT – update version 33
  • 34. Locking APIs • EntityManager methods: lock, find, refresh • Query / TypedQuery methods: setLockMode, setHint • NamedQuery annotation: lockMode element • javax.persistence.lock.scope property • javax.persistence.lock.timeout hint • PessimisticLockException (if transaction rolls back) • LockTimeoutException (if only statement rolls back) 34
  • 35. Caching Configuration New in JPA 2.0 • EntityManager persistence context corresponds to “first level” cache • Entities managed by persistence provider • Entities read from database • Entities to be written to database • Most implementations also use second-level caches • Not always transparent to application • JPA 2.0 standardizes basic second-level cache options 35
  • 36. Standard Configuration Properties • javax.persistence.jdbc.driver • javax.persistence.jdbc.url • javax.persistence.jdbc.user • javax.persistence.jdbc.password • ... 36
  • 37. Summary of JPA 2.0 New Features • More flexible modeling capabilities • Expanded O/R mapping functionality • Additions to Java Persistence query language • Criteria API • Metamodel API • Pessimistic locking • Support for validation • Standardization of many configuration options 37
  • 38. <Insert Picture Here> Using the Latest Java Persistence API 2.0 Features Arun Gupta, Java EE & GlassFish Guy blogs.sun.com/arungupta, @arungupta