S313431 JPA 2.0 Overview

40
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.

description

JPA 2.0 Overview JavaOne Brasil

Transcript of S313431 JPA 2.0 Overview

Page 1: 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.

Page 2: S313431 JPA 2.0 Overview

<Insert Picture Here>

JavaTM Persistence API 2.0: An Overview

Ludovic ChampenoisArchitect – GlassFish, NetBeans, Eclipse

Page 3: S313431 JPA 2.0 Overview

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

Page 4: S313431 JPA 2.0 Overview

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

Page 5: S313431 JPA 2.0 Overview

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

Page 6: S313431 JPA 2.0 Overview

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)

Page 7: S313431 JPA 2.0 Overview

7

Collections of Basic Types

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

Page 8: S313431 JPA 2.0 Overview

8

Collections of Basic Types

PERSONSSN NAME BIRTHDATE

PERSON_SSN NICKNAMES PERSON_NICKNAMES

Page 9: S313431 JPA 2.0 Overview

9

Collections of Basic Types

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

Page 10: S313431 JPA 2.0 Overview

10

Collections of Basic Types

PERSONSSN NAME BIRTHDATE

ALIASES PERSON_SSN ALIAS

Page 11: S313431 JPA 2.0 Overview

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; ... }

Page 12: S313431 JPA 2.0 Overview

12

LANDLORD_TAXID STREET CITY STATE …

Collections of Embeddable Types

LANDLORD TAXID NAME …

RENTALS

Page 13: S313431 JPA 2.0 Overview

13

Persistently Ordered Lists

• Order is maintained in database by provider– Uses additional (integral) ordering column

• Specified with @OrderColumn• Provides alternative to @OrderBy

Page 14: S313431 JPA 2.0 Overview

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; ...}

Page 15: S313431 JPA 2.0 Overview

15

CARDID ID TXDATE … TXORDERCARDTRANSACTION

OrderColumn

CREDITCARD CARDNUMBER …

Page 16: S313431 JPA 2.0 Overview

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

Page 17: S313431 JPA 2.0 Overview

17

Orphan Deletion

@Entitypublic class Order { @Id int orderId; ...

@OneToMany(cascade=CascadeType.PERSIST,

orphanRemoval=true) Set<Item> items;}

Page 18: S313431 JPA 2.0 Overview

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

Page 19: S313431 JPA 2.0 Overview

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

Page 20: S313431 JPA 2.0 Overview

20

Ordered Lists, Date Literals

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

Page 21: S313431 JPA 2.0 Overview

21

Restricted Polymorphism, Collection-valued Input Parameters

SELECT eFROM Employee eWHERE TYPE(e) IN (PartTime, Contractor)

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

Page 22: S313431 JPA 2.0 Overview

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

Page 23: S313431 JPA 2.0 Overview

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

Page 24: S313431 JPA 2.0 Overview

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

Page 25: S313431 JPA 2.0 Overview

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

Page 26: S313431 JPA 2.0 Overview

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

Page 27: S313431 JPA 2.0 Overview

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

Page 28: S313431 JPA 2.0 Overview

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

Page 29: S313431 JPA 2.0 Overview

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

Page 30: S313431 JPA 2.0 Overview

30

Example: Entity Class

@Entity

public class Customer {

@Id int id;

String name;

Address address;

...

@OneToMany Set<Order> orders;

@ManyToOne SalesRep rep;

...

}

Page 31: S313431 JPA 2.0 Overview

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;

...

}

Page 32: S313431 JPA 2.0 Overview

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

Page 33: S313431 JPA 2.0 Overview

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

Page 34: S313431 JPA 2.0 Overview

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)

Page 35: S313431 JPA 2.0 Overview

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

Page 36: S313431 JPA 2.0 Overview

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; ...}

Page 37: S313431 JPA 2.0 Overview

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

Page 38: S313431 JPA 2.0 Overview

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)

Page 39: S313431 JPA 2.0 Overview

39

Page 40: S313431 JPA 2.0 Overview

40