SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera, Inc.
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data opsmnacos
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalFredric Mitchell
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageRonald Ashri
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingmichid
 
Managing OpenAFS users with OpenIDM
Managing OpenAFS users with OpenIDMManaging OpenAFS users with OpenIDM
Managing OpenAFS users with OpenIDMManfred Furuholmen
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data ModelAttila Jenei
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7Zsolt Tasnadi
 
The Power of MySQL Explain
The Power of MySQL ExplainThe Power of MySQL Explain
The Power of MySQL ExplainMYXPLAIN
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comJD Leonard
 
Pursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPPursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPGiorgio Sironi
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Nuxeo
 

La actualidad más candente (20)

Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
Entity api
Entity apiEntity api
Entity api
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
Cloudera Sessions - Clinic 3 - Advanced Steps - Fast-track Development for ET...
 
Erlang for data ops
Erlang for data opsErlang for data ops
Erlang for data ops
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
Drupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of UsageDrupal Entities - Emerging Patterns of Usage
Drupal Entities - Emerging Patterns of Usage
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Managing OpenAFS users with OpenIDM
Managing OpenAFS users with OpenIDMManaging OpenAFS users with OpenIDM
Managing OpenAFS users with OpenIDM
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
The Power of MySQL Explain
The Power of MySQL ExplainThe Power of MySQL Explain
The Power of MySQL Explain
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
Pursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHPPursuing practices of Domain-Driven Design in PHP
Pursuing practices of Domain-Driven Design in PHP
 
Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS Devoxx08 - Nuxeo Core, JCR 2, CMIS
Devoxx08 - Nuxeo Core, JCR 2, CMIS
 

Destacado

GlassFish Tool Bundle for Eclipse
GlassFish Tool Bundle for EclipseGlassFish Tool Bundle for Eclipse
GlassFish Tool Bundle for EclipseLudovic Champenois
 
Java EE 6, Eclipse, GlassFish @EclipseCon 2010
Java EE 6, Eclipse, GlassFish @EclipseCon 2010Java EE 6, Eclipse, GlassFish @EclipseCon 2010
Java EE 6, Eclipse, GlassFish @EclipseCon 2010Ludovic Champenois
 
How To Make A Great Pbj
How To Make A Great PbjHow To Make A Great Pbj
How To Make A Great Pbjguest861d7
 
Ad Tech 2011 - In Store Digital Leadership
Ad Tech 2011 - In Store Digital LeadershipAd Tech 2011 - In Store Digital Leadership
Ad Tech 2011 - In Store Digital LeadershipBrad Locke
 
Abusive Training Certificate 3 18 2014
Abusive Training Certificate 3 18 2014Abusive Training Certificate 3 18 2014
Abusive Training Certificate 3 18 2014colleenmcg
 
GlassFish v3, OSGi Equinox Felix
GlassFish v3, OSGi Equinox FelixGlassFish v3, OSGi Equinox Felix
GlassFish v3, OSGi Equinox FelixLudovic Champenois
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesLudovic Champenois
 

Destacado (8)

GlassFish Tool Bundle for Eclipse
GlassFish Tool Bundle for EclipseGlassFish Tool Bundle for Eclipse
GlassFish Tool Bundle for Eclipse
 
Java EE 6, Eclipse, GlassFish @EclipseCon 2010
Java EE 6, Eclipse, GlassFish @EclipseCon 2010Java EE 6, Eclipse, GlassFish @EclipseCon 2010
Java EE 6, Eclipse, GlassFish @EclipseCon 2010
 
How To Make A Great Pbj
How To Make A Great PbjHow To Make A Great Pbj
How To Make A Great Pbj
 
Ad Tech 2011 - In Store Digital Leadership
Ad Tech 2011 - In Store Digital LeadershipAd Tech 2011 - In Store Digital Leadership
Ad Tech 2011 - In Store Digital Leadership
 
Abusive Training Certificate 3 18 2014
Abusive Training Certificate 3 18 2014Abusive Training Certificate 3 18 2014
Abusive Training Certificate 3 18 2014
 
GlassFish v3, OSGi Equinox Felix
GlassFish v3, OSGi Equinox FelixGlassFish v3, OSGi Equinox Felix
GlassFish v3, OSGi Equinox Felix
 
JavaEE 6 tools coverage
JavaEE 6 tools coverageJavaEE 6 tools coverage
JavaEE 6 tools coverage
 
JAX-RS Creating RESTFul services
JAX-RS Creating RESTFul servicesJAX-RS Creating RESTFul services
JAX-RS Creating RESTFul services
 

Similar a S313431 JPA 2.0 Overview

Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaArun Gupta
 
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 OverviewSanjeeb Sahoo
 
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
 
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
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdfssuser0562f1
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
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 WolffJAX London
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSimonPilkington8
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
 
Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015eddiebaggott
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCAndy Butland
 

Similar a S313431 JPA 2.0 Overview (20)

Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
 
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
 
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
 
Jpa
JpaJpa
Jpa
 
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)
 
springdatajpa-up.pdf
springdatajpa-up.pdfspringdatajpa-up.pdf
springdatajpa-up.pdf
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
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
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS Technologies
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015Dublin Ireland Spark Meetup October 15, 2015
Dublin Ireland Spark Meetup October 15, 2015
 
DDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVCDDD, CQRS and testing with ASP.Net MVC
DDD, CQRS and testing with ASP.Net MVC
 
Requery overview
Requery overviewRequery overview
Requery overview
 

S313431 JPA 2.0 Overview

  • 1. 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
  • 2. <Insert Picture Here> JavaTM Persistence 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: 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
  • 6. 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
  • 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 PERSON SSN NAME BIRTHDATE PERSON_NICKNAMES PERSON_SSN NICKNAMES 8
  • 9. 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
  • 10. Collections of Basic Types PERSON SSN NAME BIRTHDATE ALIASES PERSON_SSN ALIAS 10
  • 11. 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
  • 12. Collections of Embeddable Types 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 @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
  • 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 class Order { @Id int orderId; ... @OneToMany(cascade=CascadeType.PERSIST, orphanRemoval=true) Set<Item> items; } 17
  • 18. 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
  • 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, 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
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 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 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
  • 27. 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
  • 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 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
  • 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.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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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. 39
  • 40. 40