S313431 JPA 2.0 Overview

1,401 views

Published on

JPA 2.0 Overview JavaOne Brasil

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,401
On SlideShare
0
From Embeds
0
Number of Embeds
25
Actions
Shares
0
Downloads
44
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

S313431 JPA 2.0 Overview

  1. 1. The following is intended to outline our general product direction. It is intended for informationpurposes 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. 2. <Insert Picture Here>JavaTM Persistence API 2.0: An OverviewLudovic ChampenoisArchitect – GlassFish, NetBeans, Eclipse
  3. 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. 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. 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. 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. 7. Collections of Basic Types@Entitypublic class Person { @Id protected String ssn; protected String name; protected Date birthDate; ... @ElementCollection protected Set<String> nickNames; ...} 7
  8. 8. Collections of Basic Types PERSON SSN NAME BIRTHDATE PERSON_NICKNAMES PERSON_SSN NICKNAMES 8
  9. 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; ...} 9
  10. 10. Collections of Basic Types PERSON SSN NAME BIRTHDATE ALIASES PERSON_SSN ALIAS 10
  11. 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. 12. Collections of Embeddable Types LANDLORD TAXID NAME … RENTALS LANDLORD_TAXID STREET CITY STATE … 12
  13. 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. 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. 15. OrderColumn CREDITCARD CARDNUMBER … CARDTRANSACTION CARDID ID TXDATE … TXORDER 15
  16. 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 elementcascade=CascadeType.REMOVE is redundant 16
  17. 17. Orphan Deletion@Entitypublic class Order { @Id int orderId; ... @OneToMany(cascade=CascadeType.PERSIST, orphanRemoval=true) Set<Item> items;} 17
  18. 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. 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. 20. Ordered Lists, Date LiteralsSELECT tFROM CreditCard c JOIN c.transactionHistory tWHERE c.customer.name = John Doe AND INDEX(t) < 100 AND t.txDate <= {d 2010-6-30} 20
  21. 21. Restricted Polymorphism,Collection-valued Input ParametersSELECT eFROM Employee eWHERE TYPE(e) IN (PartTime, Contractor)SELECT eFROM Employee eWHERE TYPE(e) IN :empTypes 21
  22. 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. 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. 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. 25. How to Build (and Execute) a Criteria QueryCriteriaBuilder 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. 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. 27. Joins and NavigationSELECT cFROM Customer c join c.orders oCriteriaBuilder 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. 28. Joins and Navigation: What’s the Problem?SELECT cFROM Customer c join c.orders oCriteriaBuilder 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. 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. 30. Example: Entity Class @Entity public class Customer { @Id int id; String name; Address address; ... @OneToMany Set<Order> orders; @ManyToOne SalesRep rep; ... } 30
  31. 31. Example: Canonical Static Metamodel Classimport 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. 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. 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. 34. Additional Standardized Configuration Optionsjavax.persistence.jdbc.driverjavax.persistence.jdbc.urljavax.persistence.jdbc.userjavax.persistence.jdbc.passwordjavax.persistence.lock.timeoutjavax.persistence.query.timeout…(in persistence.xml) 34
  35. 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. 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. 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. 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. 39
  40. 40. 40

×