The following is intended to outline our general
 product direction. It is intended for information
purposes only, and may not be incorporated into
  any contract. It is not a commitment to deliver
 any material, code, or functionality, and should
     not be relied upon in making purchasing
                      decisions.
   The development, release, and timing of any
 features or functionality described for Oracle’s
    products remains at the sole discretion of
                       Oracle.


                                                     1
<Insert Picture Here>




JavaTM Persistence API 2.0: An Overview
Ludovic Champenois
Architect – GlassFish, NetBeans, Eclipse
JavaTM Persistence API: Brief History


• Java Persistence 1.0
   – Standardized object/relational mapping for Java applications
   – Available as part Java EE 5 Platform or standalone
   – Covered most of the essential features
• Java Persistence 2.0
   –   More and better       increased application portability
   –   Released in December 2009
   –   Available as part of Java EE 6 Platform or standalone
   –   Reference Implementation is EclipseLink
   –   Available as part of GlassFish v3




                                                                    3
JavaTM Persistence 2.0: New Features


• Expanded modeling capabilities
• Additional O/R mapping options
• Additions to Java Persistence query language
• Criteria API
• Metamodel API
• Pessimistic locking
• Support for Bean Validation




                                                 4
JavaTM Persistence 2.0:
Expanded modeling and mapping

• Collections of basic types
• Collections of embeddables
• Richer support for embeddable classes
   – Multiple levels of embedding
   – Embeddable classes with relationships
• Persistently ordered lists
• Improved map support
   – Joins with additional columns
   – Ternary relationships
• Orphan deletion



                                             5
Collections of Basic Types and Embeddables


• Collections of strings, integers, etc.
• Collections of embeddables (e.g., Address, Detail)
• Specified by @ElementCollection
• Stored in “collection table”
• Customize mappings with:
  – @CollectionTable
  – @Column (for basic types)
  – @AttributeOverride, @AssociationOverride (for embeddables)




                                                                 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




   PERSON
   SSN   NAME    BIRTHDATE




                 PERSON_NICKNAMES
                 PERSON_SSN   NICKNAMES




                                          8
Collections of Basic Types


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



                                       9
Collections of Basic Types




   PERSON
   SSN   NAME    BIRTHDATE




                 ALIASES
                 PERSON_SSN   ALIAS




                                      10
Collections of Embeddable Types

@Entity public class Landlord {
    @Id String taxId;
    String name;
    @ElementCollection
    @CollectionTable(name=“rentals”)
    Set<Address> properties;
    ...
}

@Embeddable public class Address {
    String street;
    String city;
    String state;
    ...
}
                                       11
Collections of Embeddable Types




  LANDLORD
  TAXID   NAME       …




           RENTALS
          LANDLORD_TAXID   STREET   CITY   STATE   …




                                                       12
Persistently Ordered Lists


• Order is maintained in database by provider
   – Uses additional (integral) ordering column
• Specified with @OrderColumn
• Provides alternative to @OrderBy




                                                  13
Persistently Ordered Lists

@Entity public class CreditCard {
   @Id String cardNumber;
   @ManyToOne Customer customer;
   ...
   @OneToMany(mappedBy=“creditCard”)
   @OrderColumn(name=“TXORDER”)
   List<CardTransaction> transactionHistory;
   ...
}

@Entity public class CardTransaction {
    @Id @GeneratedValue Long id;
    @ManyToOne @JoinColumn(name=“CARDID”)
    CreditCard creditCard;
    @Temporal(DATE) Date txDate;
    ...
}
                                               14
OrderColumn




 CREDITCARD
 CARDNUMBER   …




              CARDTRANSACTION
              CARDID   ID   TXDATE   …   TXORDER




                                                   15
Automatic Orphan Deletion


• Deletion of related entities when removed from
 relationship or when referencing entity is removed
  – For entities logically “owned” by “parent”
  – For one-to-one and one-to-many relationships
• Specified with orphanRemoval element
cascade=CascadeType.REMOVE is redundant




                                                      16
Orphan Deletion


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




                                              17
Java Persistence Query Language:
New Functionality

• Support for all new modeling and mapping features
• Operators and functions in select list
• Case, coalesce, nullif expressions
• Restricted polymorphism
• Collection-valued input parameters
• Date / time / timestamp literals




                                                      18
New Operators


• INDEX
   – For ordered lists
• KEY, VALUE, ENTRY
  – For maps
• CASE, COALESCE, NULLIF
   – For case expressions and the like
• TYPE
  – For entity type expressions / restricted polymorphism




                                                            19
Ordered Lists, Date Literals


SELECT t
FROM CreditCard c JOIN c.transactionHistory t
WHERE c.customer.name = 'John Doe'
  AND INDEX(t) < 100
  AND t.txDate <= {d '2010-6-30'}




                                                20
Restricted Polymorphism,
Collection-valued Input Parameters

SELECT e
FROM Employee e
WHERE TYPE(e) IN (PartTime, Contractor)


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




                                          21
Criteria API


• Object-based API for building queries
• Designed to mirror JPQL semantics
• Strongly typed
   – Heavy use of Java generics
   – Based on type-safe metamodel of persistence unit
   – Typing carries through to query execution as well
• Supports object-based or string-based navigation




                                                         22
Criteria API: Core Interfaces


• CriteriaQuery
   – Represents a query definition object
   – Used to add / replace / browse constituent query elements
   – select, from, where, orderBy, groupBy, having,… methods
• CriteriaBuilder
  – Factory for CriteriaQuery objects
  – Obtained from EntityManager or EntityManagerFactory
  – Used to create selections, expressions, restrictions, orderings…
• Root
   – Query root




                                                                       23
Criteria API: Core Interfaces


• Join, ListJoin, MapJoin,…
   – Joins from a root or existing join
• Path
   – Navigation from a root, join, path
• Subquery
• Parameter
• TypedQuery
   – Executable query object
   – Extends Query interface
• Tuple
   – Multiple-valued result type


                                          24
How to Build (and Execute) a Criteria Query
CriteriaBuilder cb = ...;
CriteriaQuery<ResultType> cq =
  cb.createQuery(ResultType.class);
Root<SomeEntity> e = cq.from(SomeEntity.class);
Join<SomeEntity,RelatedEntity> j = e.join(...);
...
// the following in any order:
cq.select(…)
   .where(…)
   .orderBy(…)
   .groupBy(…)
   .having(…);
TypedQuery<ResultType> tq = em.createQuery(cq);
List<ResultType> results = tq.getResultList();

                                                  25
The World’s Simplest Query

  SELECT c
  FROM Customer c


   CriteriaBuilder cb = em.getCriteriaBuilder();
  CriteriaQuery<Customer> cq =
   cb.createQuery(Customer.class);
  Root<Customer> c = cq.from(Customer.class);
  cq.select(c);
  List<Customer> result =
   em.createQuery(cq).getResultList();


                                                26
Joins and Navigation



SELECT c
FROM Customer c join c.orders o

CriteriaBuilder cb = ...;
CriteriaQuery<Customer> cq =
  cb.createQuery(Customer.class);
Root<Customer> c = cq.from(Customer.class);
Join<Customer, Order> o = customer.join(“orders”);
cq.select(c);




                                                     27
Joins and Navigation: What’s the Problem?



SELECT c
FROM Customer c join c.orders o

CriteriaBuilder cb = ...;
CriteriaQuery<Customer> cq =
 cb.createQuery(Customer.class);
Root<Customer> c = cq.from(Customer.class);
Join<Customer, Order> o = customer.join(“wombats”);
cq.select(c);




                                                      28
Metamodel


• Abstract, “schema-level” view of managed classes of
 persistence unit
  – Entities, mapped superclasses, embeddables, and their
    attributes and relationships
• Accessible at runtime
   – EntityManagerFactory.getMetamodel()
   – EntityManager.getMetamodel()
• Useful for frameworks
• Provides foundation for type-safe queries
• Can be materialized as static metamodel classes
  – Use javac + annotation processor


                                                            29
Example: Entity Class


  @Entity
  public class Customer {
      @Id int id;
      String name;
      Address address;
      ...
      @OneToMany Set<Order> orders;
      @ManyToOne SalesRep rep;
      ...
  }


                                      30
Example: Canonical Static Metamodel Class


import javax.persistence.metamodel.*


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




                                                                        31
Type-safe Navigation


  SELECT c
  FROM Customer c join c.orders o

  CriteriaBuilder cb = ...;
  CriteriaQuery<Customer> cq   = cb.createQuery(Customer.class);
  Root<Customer> c = cq.from(Customer.class);
  Join<Customer, Order> o = customer.join(Customer_.orders);
  cq.select(c);




                                                                   32
Locking


• JPA 1.0 only supported optimistic read or optimistic
  write locking
   – At commit time, JPA checked the version Attribute
   – Assumed infrequent conflicts
• JPA 2.0 introduces Pessimistic locking
   – A transaction that reads data locks it
   – Another transaction cannot change it before the 1rst
     transaction commits the read
   – Assume frequent conflicts
• In total, now 5 lock modes
   – Optimistic, Optimistic_force_increment, Pessimistic_read,
     Pessimistic_write, Pessimistic_force_increment

                                                                 33
Additional Standardized Configuration Options


javax.persistence.jdbc.driver
javax.persistence.jdbc.url
javax.persistence.jdbc.user
javax.persistence.jdbc.password
javax.persistence.lock.timeout
javax.persistence.query.timeout
…(in persistence.xml)




                                                34
Bean Validation


• Leverages work of Bean Validation JSR (JSR 303)
• Automatic validation upon lifecycle events
  – PrePersist
  – PreUpdate
  – PreRemove
• persistence.xml validation-mode element
   – AUTO
   – CALLBACK
   – NONE




                                                    35
Bean Validation

@Entity public class Employee {
    @Id Integer empId;
    @NotNull String name;
    Float salary;
    @Max(15) Integer vacationDays;
    @Valid Address worksite;
    ...
}

@Embeddable public class Address {
    @Size(max=30) String street;
    @Size(max=20) String city;
    @Size(min=2,max=2) String state;
    @Zipcode String zipcode;
    ...
}
                                       36
Summary


• Expanded modeling capabilities
• Additional O/R mapping options
• Additions to Java Persistence query language
• Metamodel API
• Criteria API
• Pessimistic locking
• Support for validation
• Improved portability




                                                 37
Resources


• Java Persistence 2.0 Specification
    http://jcp.org/en/jsr/detail?id=317
• Reference Implementation is EclipseLink
    http://www.eclipse.org/eclipselink
• Available as part of Java EE 6 with GlassFish
    http://glassfish.org
• Book: Pro JPA 2 (Keith & Schincariol)




                                                  38
39
40

S313431 JPA 2.0 Overview

  • 1.
    The following isintended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 1
  • 2.
    <Insert Picture Here> JavaTMPersistence API 2.0: An Overview Ludovic Champenois Architect – GlassFish, NetBeans, Eclipse
  • 3.
    JavaTM Persistence API:Brief History • Java Persistence 1.0 – Standardized object/relational mapping for Java applications – Available as part Java EE 5 Platform or standalone – Covered most of the essential features • Java Persistence 2.0 – More and better increased application portability – Released in December 2009 – Available as part of Java EE 6 Platform or standalone – Reference Implementation is EclipseLink – Available as part of GlassFish v3 3
  • 4.
    JavaTM Persistence 2.0:New Features • Expanded modeling capabilities • Additional O/R mapping options • Additions to Java Persistence query language • Criteria API • Metamodel API • Pessimistic locking • Support for Bean Validation 4
  • 5.
    JavaTM Persistence 2.0: Expandedmodeling and mapping • Collections of basic types • Collections of embeddables • Richer support for embeddable classes – Multiple levels of embedding – Embeddable classes with relationships • Persistently ordered lists • Improved map support – Joins with additional columns – Ternary relationships • Orphan deletion 5
  • 6.
    Collections of BasicTypes and Embeddables • Collections of strings, integers, etc. • Collections of embeddables (e.g., Address, Detail) • Specified by @ElementCollection • Stored in “collection table” • Customize mappings with: – @CollectionTable – @Column (for basic types) – @AttributeOverride, @AssociationOverride (for embeddables) 6
  • 7.
    Collections of BasicTypes @Entity public class Person { @Id protected String ssn; protected String name; protected Date birthDate; ... @ElementCollection protected Set<String> nickNames; ... } 7
  • 8.
    Collections of BasicTypes PERSON SSN NAME BIRTHDATE PERSON_NICKNAMES PERSON_SSN NICKNAMES 8
  • 9.
    Collections of BasicTypes @Entity public class Person { @Id protected String ssn; protected String name; protected Date birthDate; ... @ElementCollection @CollectionTable(name=“ALIASES”) @Column(name=“ALIAS”) protected Set<String> nickNames; ... } 9
  • 10.
    Collections of BasicTypes PERSON SSN NAME BIRTHDATE ALIASES PERSON_SSN ALIAS 10
  • 11.
    Collections of EmbeddableTypes @Entity public class Landlord { @Id String taxId; String name; @ElementCollection @CollectionTable(name=“rentals”) Set<Address> properties; ... } @Embeddable public class Address { String street; String city; String state; ... } 11
  • 12.
    Collections of EmbeddableTypes LANDLORD TAXID NAME … RENTALS LANDLORD_TAXID STREET CITY STATE … 12
  • 13.
    Persistently Ordered Lists •Order is maintained in database by provider – Uses additional (integral) ordering column • Specified with @OrderColumn • Provides alternative to @OrderBy 13
  • 14.
    Persistently Ordered Lists @Entitypublic class CreditCard { @Id String cardNumber; @ManyToOne Customer customer; ... @OneToMany(mappedBy=“creditCard”) @OrderColumn(name=“TXORDER”) List<CardTransaction> transactionHistory; ... } @Entity public class CardTransaction { @Id @GeneratedValue Long id; @ManyToOne @JoinColumn(name=“CARDID”) CreditCard creditCard; @Temporal(DATE) Date txDate; ... } 14
  • 15.
    OrderColumn CREDITCARD CARDNUMBER … CARDTRANSACTION CARDID ID TXDATE … TXORDER 15
  • 16.
    Automatic Orphan Deletion •Deletion of related entities when removed from relationship or when referencing entity is removed – For entities logically “owned” by “parent” – For one-to-one and one-to-many relationships • Specified with orphanRemoval element cascade=CascadeType.REMOVE is redundant 16
  • 17.
    Orphan Deletion @Entity public classOrder { @Id int orderId; ... @OneToMany(cascade=CascadeType.PERSIST, orphanRemoval=true) Set<Item> items; } 17
  • 18.
    Java Persistence QueryLanguage: New Functionality • Support for all new modeling and mapping features • Operators and functions in select list • Case, coalesce, nullif expressions • Restricted polymorphism • Collection-valued input parameters • Date / time / timestamp literals 18
  • 19.
    New Operators • INDEX – For ordered lists • KEY, VALUE, ENTRY – For maps • CASE, COALESCE, NULLIF – For case expressions and the like • TYPE – For entity type expressions / restricted polymorphism 19
  • 20.
    Ordered Lists, DateLiterals SELECT t FROM CreditCard c JOIN c.transactionHistory t WHERE c.customer.name = 'John Doe' AND INDEX(t) < 100 AND t.txDate <= {d '2010-6-30'} 20
  • 21.
    Restricted Polymorphism, Collection-valued InputParameters SELECT e FROM Employee e WHERE TYPE(e) IN (PartTime, Contractor) SELECT e FROM Employee e WHERE TYPE(e) IN :empTypes 21
  • 22.
    Criteria API • Object-basedAPI for building queries • Designed to mirror JPQL semantics • Strongly typed – Heavy use of Java generics – Based on type-safe metamodel of persistence unit – Typing carries through to query execution as well • Supports object-based or string-based navigation 22
  • 23.
    Criteria API: CoreInterfaces • CriteriaQuery – Represents a query definition object – Used to add / replace / browse constituent query elements – select, from, where, orderBy, groupBy, having,… methods • CriteriaBuilder – Factory for CriteriaQuery objects – Obtained from EntityManager or EntityManagerFactory – Used to create selections, expressions, restrictions, orderings… • Root – Query root 23
  • 24.
    Criteria API: CoreInterfaces • Join, ListJoin, MapJoin,… – Joins from a root or existing join • Path – Navigation from a root, join, path • Subquery • Parameter • TypedQuery – Executable query object – Extends Query interface • Tuple – Multiple-valued result type 24
  • 25.
    How to Build(and Execute) a Criteria Query CriteriaBuilder cb = ...; CriteriaQuery<ResultType> cq = cb.createQuery(ResultType.class); Root<SomeEntity> e = cq.from(SomeEntity.class); Join<SomeEntity,RelatedEntity> j = e.join(...); ... // the following in any order: cq.select(…) .where(…) .orderBy(…) .groupBy(…) .having(…); TypedQuery<ResultType> tq = em.createQuery(cq); List<ResultType> results = tq.getResultList(); 25
  • 26.
    The World’s SimplestQuery SELECT c FROM Customer c CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Customer> cq = cb.createQuery(Customer.class); Root<Customer> c = cq.from(Customer.class); cq.select(c); List<Customer> result = em.createQuery(cq).getResultList(); 26
  • 27.
    Joins and Navigation SELECTc FROM Customer c join c.orders o CriteriaBuilder cb = ...; CriteriaQuery<Customer> cq = cb.createQuery(Customer.class); Root<Customer> c = cq.from(Customer.class); Join<Customer, Order> o = customer.join(“orders”); cq.select(c); 27
  • 28.
    Joins and Navigation:What’s the Problem? SELECT c FROM Customer c join c.orders o CriteriaBuilder cb = ...; CriteriaQuery<Customer> cq = cb.createQuery(Customer.class); Root<Customer> c = cq.from(Customer.class); Join<Customer, Order> o = customer.join(“wombats”); cq.select(c); 28
  • 29.
    Metamodel • Abstract, “schema-level”view of managed classes of persistence unit – Entities, mapped superclasses, embeddables, and their attributes and relationships • Accessible at runtime – EntityManagerFactory.getMetamodel() – EntityManager.getMetamodel() • Useful for frameworks • Provides foundation for type-safe queries • Can be materialized as static metamodel classes – Use javac + annotation processor 29
  • 30.
    Example: Entity Class @Entity public class Customer { @Id int id; String name; Address address; ... @OneToMany Set<Order> orders; @ManyToOne SalesRep rep; ... } 30
  • 31.
    Example: Canonical StaticMetamodel Class import javax.persistence.metamodel.* @Generated(“EclipseLink JPA 2.0 Canonical Model Generation”) @StaticMetamodel(Customer.class) public class Customer_ { public static volatile SingularAttribute<Customer, Integer> id; public static volatile SingularAttribute<Customer, String> name; public static volatile SingularAttribute<Customer, Address> address; public static volatile SetAttribute<Customer, Order> orders; public static volatile SingularAttribute<Customer, SalesRep> rep; ... } 31
  • 32.
    Type-safe Navigation SELECT c FROM Customer c join c.orders o CriteriaBuilder cb = ...; CriteriaQuery<Customer> cq = cb.createQuery(Customer.class); Root<Customer> c = cq.from(Customer.class); Join<Customer, Order> o = customer.join(Customer_.orders); cq.select(c); 32
  • 33.
    Locking • JPA 1.0only supported optimistic read or optimistic write locking – At commit time, JPA checked the version Attribute – Assumed infrequent conflicts • JPA 2.0 introduces Pessimistic locking – A transaction that reads data locks it – Another transaction cannot change it before the 1rst transaction commits the read – Assume frequent conflicts • In total, now 5 lock modes – Optimistic, Optimistic_force_increment, Pessimistic_read, Pessimistic_write, Pessimistic_force_increment 33
  • 34.
    Additional Standardized ConfigurationOptions javax.persistence.jdbc.driver javax.persistence.jdbc.url javax.persistence.jdbc.user javax.persistence.jdbc.password javax.persistence.lock.timeout javax.persistence.query.timeout …(in persistence.xml) 34
  • 35.
    Bean Validation • Leverageswork of Bean Validation JSR (JSR 303) • Automatic validation upon lifecycle events – PrePersist – PreUpdate – PreRemove • persistence.xml validation-mode element – AUTO – CALLBACK – NONE 35
  • 36.
    Bean Validation @Entity publicclass Employee { @Id Integer empId; @NotNull String name; Float salary; @Max(15) Integer vacationDays; @Valid Address worksite; ... } @Embeddable public class Address { @Size(max=30) String street; @Size(max=20) String city; @Size(min=2,max=2) String state; @Zipcode String zipcode; ... } 36
  • 37.
    Summary • Expanded modelingcapabilities • Additional O/R mapping options • Additions to Java Persistence query language • Metamodel API • Criteria API • Pessimistic locking • Support for validation • Improved portability 37
  • 38.
    Resources • Java Persistence2.0 Specification http://jcp.org/en/jsr/detail?id=317 • Reference Implementation is EclipseLink http://www.eclipse.org/eclipselink • Available as part of Java EE 6 with GlassFish http://glassfish.org • Book: Pro JPA 2 (Keith & Schincariol) 38
  • 39.
  • 40.