Java Persistence API 2.0: An Overview

50
<Insert Picture Here> Java TM Persistence API 2.0: An Overview Sanjeeb Sahoo Sr. Staff Engineer, Sun, an Oracle Company

description

Presentation made at JavaONE, Hyderabad, on 10th May 2011. Slides are a slightly modified version of what&#x27;s presented by Linda D. at JavaONE, SF, in 2010.

Transcript of Java Persistence API 2.0: An Overview

Page 1: Java Persistence API 2.0: An Overview

<Insert Picture Here>

JavaTM Persistence API 2.0: An Overview

Sanjeeb SahooSr. Staff Engineer, Sun, an Oracle Company

Page 2: Java Persistence API 2.0: An Overview

2

The following/preceding 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 3: Java Persistence API 2.0: An 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: Java Persistence API 2.0: An Overview

4

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

Page 5: Java Persistence API 2.0: An Overview

5

Packaging

• Java SE (Standalone Java Application)– Jar file with entities, application classes and META-

INF/persistence.xml

• Java EE– War file

• WEB-INF/classes/META-INF/persistence.xml• WEB-INF/lib/entities.jar (with META-INF/persistence.xml)

– EJB jar• EJBs and entities and META-INF/persistence.xml

– EAR file• lib/entities.jar with META-INF/persistence.xml

Page 6: Java Persistence API 2.0: An Overview

6

Bootstrapping

• Java SE (Standalone Java Application)– Persistence.createEntityManagerFactory

• Java EE– @PersistenceContext EntityManager em;– @PersistenceUnit EntityManagerFactory emf;

Page 7: Java Persistence API 2.0: An Overview

7

JavaTM Persistence 2.0:New Features

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

Page 8: Java Persistence API 2.0: An Overview

8

Object/Relational MappingEssentials

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

Page 9: Java Persistence API 2.0: An Overview

9

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 10: Java Persistence API 2.0: An Overview

10

JavaTM Persistence 2.0: Expanded modeling and mapping

• Derived identities– Improved modeling for overlapping primary and foreign

keys

• Combinations of access types• Expanded relationship mapping options

– Unidirectional one-many foreign key mappings– One-one, many-one/one-many join table mappings

Page 11: Java Persistence API 2.0: An Overview

11

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 12: Java Persistence API 2.0: An Overview

12

Collections of Basic Types

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

Page 13: Java Persistence API 2.0: An Overview

13

Collections of Basic Types

PERSONSSN NAME BIRTHDATE

PERSON_SSN NICKNAMES PERSON_NICKNAMES

Page 14: Java Persistence API 2.0: An Overview

14

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 15: Java Persistence API 2.0: An Overview

15

LANDLORD_TAXID STREET CITY STATE …

Collections of Embeddable Types

LANDLORD TAXID NAME …

RENTALS

Page 16: Java Persistence API 2.0: An Overview

16

Multiple Levels of Embedding

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

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

Page 17: Java Persistence API 2.0: An Overview

17

Embeddables with Relationships

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

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

Page 18: Java Persistence API 2.0: An Overview

18

Persistently Ordered Lists

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

• Specified with @OrderColumn• Provides alternative to @OrderBy

Page 19: Java Persistence API 2.0: An Overview

19

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 20: Java Persistence API 2.0: An Overview

20

CARDID ID TXDATE … TXORDERCARDTRANSACTION

OrderColumn

CREDITCARD CARDNUMBER …

Page 21: Java Persistence API 2.0: An Overview

21

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

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

@OrderBy Alternative

Page 22: Java Persistence API 2.0: An Overview

22

Generalized Maps

• Map key can be– Basic type– Embeddable– Entity

• Map value can be– Basic type– Embeddable– Entity

• Support for legacy join tables with additional columns

• Support for ternary relationships

Page 23: Java Persistence API 2.0: An Overview

23

Generalized Maps

• Map collection is specified with– @ElementCollection, @OneToMany, @ManyToMany– Annotation is determined by map value

• Customize mapping with:– @CollectionTable (for element collection)– @JoinTable (for relationship)– @MapKeyColumn (for basic map key)– @MapKeyJoinColumn(s) (for entity key)– @AttributeOverride(s) using “key.” or “value.” syntax

(for embeddables)

Page 24: Java Persistence API 2.0: An Overview

24

Generalized Maps

@Entitypublic class VideoStore { @Id Integer storeId; Address location; @ElementCollection @CollectionTable( joinColumn=@JoinColumn(name=“VIDEO_STOREID”)) Map<Movie, Integer> inventory; ...}

@Entitypublic class Movie { @Id String title; String director; ...}

Page 25: Java Persistence API 2.0: An Overview

25

VIDEO_STOREID INVENTORY_KEY INVENTORYVIDEOSTORE_INVENTORY

Generalized Maps

VIDEOSTORESTOREID NAME STREET CITY STATE …

MOVIE TITLE DIRECTOR …

Page 26: Java Persistence API 2.0: An Overview

26

Automatic Orphan Deletion

• Deletion of related entities when removed from relationship– For entities logically “owned” by “parent”– For one-to-one and one-to-many relationships

• Specified with orphanRemoval element– cascade=REMOVE is redundant

Page 27: Java Persistence API 2.0: An Overview

27

Orphan Deletion

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

Page 28: Java Persistence API 2.0: An Overview

28

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 29: Java Persistence API 2.0: An Overview

29

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 30: Java Persistence API 2.0: An Overview

30

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 31: Java Persistence API 2.0: An Overview

31

Criteria API

• Object-based API for building queries• Designed to mirror JPQL semantics• Strongly typed

– Based on type-safe metamodel of persistence unit– Heavy use of Java generics– Typing carries through to query execution as well

• Supports object-based or strong-based navigation

Page 32: Java Persistence API 2.0: An Overview

32

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 33: Java Persistence API 2.0: An Overview

33

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 34: Java Persistence API 2.0: An Overview

34

The World’s Simplest Query

SELECT c

FROM Customer c

CriteriaBuilder cb = ...;

CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);

Root<Customer> c = cq.from(Customer.class);

cq.select(c);

Page 35: Java Persistence API 2.0: An Overview

35

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 36: Java Persistence API 2.0: An Overview

36

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 37: Java Persistence API 2.0: An Overview

37

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 38: Java Persistence API 2.0: An Overview

38

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 39: Java Persistence API 2.0: An Overview

39

Optimistic Locking

• Assumes read-committed isolation, deferred writes– Short term read-locks– Long term write-locks

• Layered on top of @Version use– Verify version for updated entities before transaction

commit

• Lock Modes– OPTIMISTIC (READ)– OPTIMISTIC_FORCE_INCREMENT (WRITE)

• “READ” lock => verify version for clean data• “WRITE” lock => update version for clean data

Page 40: Java Persistence API 2.0: An Overview

40

Pessimistic Locking

• Grab database locks upfront• Lock Modes

– PESSIMISTIC_READ– PESSIMISTIC_WRITE– PESSIMISTIC_FORCE_INCREMENT

• Normal (default) pessimistic locking– Persistent state of entity (except element collections)– Relationships where entity holds foreign key

• Extended pessimistic locking– Uses javax.persistence.lock.scope property (EXTENDED)– Element collections and relationships in join tables– Phantoms are possible

Page 41: Java Persistence API 2.0: An Overview

41

Pessimistic Locking

@Stateless public class HRBean { ... @PersistenceContext EntityManager em; ... public void giveRaises(int deptId) { Department dept = em.find(Department.class, deptId, LockModeType.PESSIMISTIC_READ); if (dept.getBudget() > 100000) { Query q = em.createQuery( “SELECT emp ” + “FROM Employee emp ” + “WHERE emp.dept.id = ” + deptId); q.setLockMode(LockModeType.PESSIMISTIC_WRITE); List = q.getResultList(); // update employee salaries selectively... } }}

Page 42: Java Persistence API 2.0: An Overview

42

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)

Page 43: Java Persistence API 2.0: An Overview

43

Second Level Cache APIs

• APIs and control options added for portability• Cache interface methods: evict, evictAll, contains• @Cacheable + shared-cache-mode XML element

– ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE

• Properties for find, refresh, setProperty methods– javax.persistence.cache.retrieveMode property

• USE, BYPASS– javax.persistence.cache.storeMode property

• USE, BYPASS, REFRESH

Page 44: Java Persistence API 2.0: An Overview

44

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 45: Java Persistence API 2.0: An Overview

45

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 46: Java Persistence API 2.0: An Overview

46

Standard Configuration Properties

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

Page 47: Java Persistence API 2.0: An Overview

47

JPA 2.1 Candidate Featureshttp://jcp.org/en/jsr/detail?id=338

Multi-tenancy Support for stored procedures, vendor function Update and Delete Criteria queries, JPQL ↔

Criteria Query by Example Support for schema generation UUID generator type Persistence Context synchronization control Dynamic definition of PU Additional event listeners

NEW

Page 48: Java Persistence API 2.0: An Overview

48

Summary

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

Page 49: Java Persistence API 2.0: An Overview

49

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 50: Java Persistence API 2.0: An Overview

50

The following/preceding 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.