JPA 2.0

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Notes on slide 1

    These defined properties must be implemented by each vendor (aside from vendor specific properties)

    Let op! Mark @Transient anderswordtdezewegens default FIELD access ookgepersisteerd.

    2 Favorites

    JPA 2.0 - Presentation Transcript

    1. JPA 2.0
      What’s new?
      Emiel Paasschens
      Ref. implemenatie van EclipseLink is bijlange (met name Criteria API) nanognietaf, dus…
      GEEN Hands-On of tochwel…
    2. Programma
      • Standard properties in persistence.xml
      • Mixed @AccessType
      • Derived Identifiers
      • @ElementCollection
      • Undirectional @OneToMany / @OneToOne
      • @OrderColumn
      • Shared Cache API
      • Locking
      • JP QL
      • Expression and criteria API
      • HandsOn?
      • Drankjeaan de bar
    3. Standard properties for persistence.xml
      SE only:
      • javax.persistence.jdbc.driver fully qualified name of the driver class
      • javax.persistence.jdbc.url driver-specific URL
      • javax.persistence.jdbc.user username used by database connection
      • javax.persistence.jdbc.password password for database connection validation
       
      EE and SE:
      • javax.persistence.lock.timeoutvalue in milliseconds for pessimistic lock timeout
      • javax.persistence.query.timeoutvalue in milliseconds for query timeout
      • javax.persistence.validation.group.pre-persist groups that are targeted for validation upon the pre-persist event
      • javax.persistence.validation.group.pre-update groups that are targeted for validation upon the pre-update event
      • javax.persistence.validation.group.pre-remove groups that are targeted for validation upon the pre-remove event
    4. Mixed @AccessType
      • Property based or field based:@Access(FIELD)@Access(PROPERTY)
      • Can be mixed now! (instead of one or the other)At Entity/Class level the default Access type is defined
      • Can be set per attribute to differ from default: - on field (declaration) @Access(FIELD) access directly on instance variable by pers.prov.- on property (getter accessor) @Access(PROPERTY) access via accessor methods by pers. prov.
      • Be aware: @Access(PROPERTY):- validation/conversion logic in accessor methods is executed!- exceptions are catched and wrapped in PersistenceException, which is thrown. Transactions are marked for rollback.
      • The access type of an embeddable class is determined by the access type class in which it is embedded, independent of the containing class.
    5. Mixed @AccessType(code)
      @Entity
      @Access(FIELD)
      public class Vehicle {
      @Id
      private Long id;
      @Transient
      double fuelEfficieny;
       
      @Access(PROPERTY)
      @Column(name=”FUEL_EFF”)
      public double getDbFuelEfficiency(){
      return convertToMetric(fuelEfficieny);
      }
       
      public void setDbFuelEfficiency(double d){
      fuelEfficieny= convertToImperial(d);
      }
      }
    6. Derived Identifiers (1)
      Old JPA 1.0 way:
      • Identifiers that include a relationship
      • Require an additional foreign key field
      • Indicate one of the mappings as read only
      • Duplicate mapping info
      @Entity
      public class Part {
      @Id Integer partNo;
      @Column(name=“SUPP_ID”) @Id Integer suppId;
      ...
      @ManyToOne(insertable=false, updatable=false)
      @JoinColumn(name=“SUPP_ID”)
      Supplier supplier;
      ...
      }
    7. Derived Identifiers (2)
      The new JPA 2.0 way:
      • Identifiers can be derived from relationships
      @Entity public class Supplier {
      @Id long supId;
      String name;
      ...
      }
       
      public class PartId{
      String desc; //matches name of @Id attribute
      long sup; //matches name of @Id attribute and type of Supplier PK
      }
       
      @Entity
      @IdClass(PartId.class)
      public class Part {
      @Id String desc;
      @Id @ManyToOneSupplier sup;
      ...
      }
    8. ElementCollection
      @ElementCollection of basic types or embeddable classes with elements: - targetClass=<full classname> (required when generics are not used!) - fetch=FetchType.EAGER/LAZY (default=LAZY) (both optional)
      • Used to store a collection of an Entity in a (separate) table
      • Default tablename is _ or @CollectionTable(name=’tname’) with addition optional elements: - catalog (default=the ‘default’ catalog) - schema (default=the ‘default’ schema) - joinColumns (default=_) - uniqueConstraints (only used at table generation/DDL)
      • Can be combined with existing @Column (only with basic type) and @OrderBy annotations
      • @OrderBy with basic types collection: value is not used! (only @OrderBy)
    9. @ElementCollection(code)
      @Entity public class Person {
      @Id private Long socialSecurityNo;
      ...
      @ElementCollection
      @OrderBy("zipcode.zip ASC, zipcode.plusFour DESC")
      public Set<Address> getResidences() {...};
      ...
      }
      @Embeddable public class Address {
      protected String street;
      protected String city;
      protected String state;
      @Embedded protected Zipcodezipcode;
      }
      @Embeddable public class ZipCode {
      protected String zip;
      protected String plusFour;
      }
    10. Undirectional @OneToMany / @OneToOne
      @OneToMany Mapping with @JoinColumn on parent side:
       
      @Entity public class Vehicle {
      ...
      @OneToMany
      @JoinColumn(name=”VEHIC”)
      List<Parts> parts;
      ...
      }
       
      Also applies to @OneToOne
      With JPA 1.0 you had to define relation on both sides (necessary to specify columnname)
    11. @OrderColumn
      • @OrderColumn (invalidates @OrderBy), 0 based.
      • Stores the order in separate DB column, so preferable do not use!  insert object at begin of list causes lots of updates!
      • Elements, all optional:- name (default: _ORDER)- nullable (default: true)- insertable (default: true)- updatable (default: true)- columnDefinition (DDL for creating)- table (default: the jointable or table used for the collection)
    12. @OrderColumn(code)
      @Entity
      public class CreditCard {
      @Id Long ccNumber;
      @OneToMany // unidirectional
      @OrderColumn
      List<CardTransaction> transactionHistory;
      ...
      }
      Results in an ‘extra’ column in table of entity CardTransaction with name TRANSACTIONHISTORY_ORDER
    13. Shared Cache API
       
      public class Cache {
      public boolean contains(Class cls, Object pk);
      public void evict(Class cls, Object pk);
      public void evict(Class cls);
      public void evictAll();
      }
       
      • Exact implementation vendor dependent!
      • evict?  how about objects pointing to these evicting instances…
      • eventAllis save,
      • also contains, but what does it say…?
    14. Locking
      • new LockMode values: - OPTIMISTIC (READ) - OPTIMISTIC_FORCE_INCREMENT (WRITE) - PESSIMISTIC (*) - PESSIMISTIC_FORCE_INCREMENT (*)
      • API EntityManager: - LockModeparam added to find and refresh - Properties param added to find, refresh and lock (props are vendor dependent) - T unwrap (Class cls)  flexible vendor specific, e.g. to get DB connection - getEntityManagerFactory() - void clear(Object entity)  No sync to DB of unflushed changes!
    15. Locking (code)
      //Read, then lock (little concurrency risk)
      Account acct = em.find(Account.class, acctId);
      //Withdraw, so lock for update (little risk of stale data)
      em.lock(acct, PESSIMISTIC);
      long balance = acct.getBalance();
      acct.setBalance(balance – 100);
       
      //Read and lock at same time (no concurrency risk)
      Account acct = em.find(Account.class, acctId, PESSIMISTIC);
      //Withdraw, already locked (so no risk of stale data)
      long balance = acct.getBalance();
      acct.setBalance(balance – 100);
       
       
      //Read and then lock and refresh (no concurrency risk)
      Account acct = em.find(Account.class, acctId);
      //Withdraw, so lock and refresh (no risk of stale data)
      em.refresh(acct, PESSIMISTIC);
      long balance = acct.getBalance();
      acct.setBalance(balance – 100);
      Best approach depends upon specs & requirements!
    16. JP QL (1)
      • Timestamp literals (‘2009-07-06 17:30:00.’)
      • CLASS() in WHERE clause (kind of JP QL ‘instanceof’):SELECT e FROM Employee e WHERE CLASS(e) = FullTimeEmployee
      • Collection param from IN:SELECT e FROM Employee eWHERE e.id IN [:selectedIds]
      • INDEX in WHERE clause (e.g. to retrieve first 10 or paged getting data):SELECT e FROM Employee eWHERE INDEX(e) BETWEEN 0 AND 9
    17. JP QL (2)
      • CASE statement in WHERE clause :UPDATE Employee eSET e.salary =CASE e.rating WHEN 1 THEN e.salary * 1.1WHEN 2 THEN e.salary * 1.05ELSE e.salary * 1.01END
      • Also allowed is this variant:UPDATE Employee eSET e.salary =CASE WHEN e.rating = 1 THEN e.salary * 1.1WHEN e.rating = 2 THEN e.salary * 1.05ELSE e.salary * 1.01END
    18. Expression & criteria API (1)
      • QueryBuilderobject is the object the create queries with
      • Object Model totally been refactored (no more DomainObject or QueryDefinition objects)
      • CriteriaQueryrepresents JP QL in an object way
      • The query Root object defined by the from method and is analog to the “Employee e” in JP QL: SELECT e FROM Employee e
      • new Query object is created by passing CriteriaQuery to em.createQuery.
      • If CriteriaQuery is changed afterwards, the created Query object does not change!
    19. Expression & criteria API (2)
      • For all the JP QL where clause methods there is a equivalent method in the QueryBuilderAPI: e.gisEmpty(), between(), like(), equal(), notEqual(), selectCase,() all(), gt(), lt(), ge(), le(), etc.
      • Also applies for and(), or() and not(), methods of the QueryBuilder API
      • The same accounts for methods in the select: max(), min(), sum(), prod(), etc
      • But the orderBy(), groupBy() and having() are methods of the CriteriaQueryobject!
      • And function desc() and asc() are methods of the QueryBuilderobject !!
      Pro is type safe and no need any more to execute logic code twice when dynamically constructing a query comparing with JP QL (where one time parse is needed to construct the query query and one more to bind the bind params).
      Con : quite complex and hard to read, so from maintenance perspective…
    20. Expression & criteria API (code)
      Query q = em.createQuery(“SELECT a FROM Account a”);
      QueryBuilderqb = em.getQueryBuilder();CriteriaQuerycq = qb.create();
      Root<Account> account = cq.from(Account.class);
      cq.select(account);
      Query q = em.createQuery(cq);
      List<Account> list = q. getResultList();
       
    21. Expression & criteria API (code)
      SELECT c.name
      FROM Customer c
      JOIN c.orders o
      JOIN o.lineitemsi
      WHERE i.product.productType = ‘printer’
      CriteriaQuery q = qb.create();
      Root<Customer> cust = q.from(Customer.class);
      Join<Customer, Order> order = cust.join(Customer_.orders);
      Join<Order, Item> item = order.join(Order_.lineitems);
      q.select(cust.get(Customer_.name))
      .where(qb.equal(item.get(Item_.product).get(Product_.productType),
      "printer"));
    22. Expression & criteria API (code)
      Joins can be chained, resulting into:
       CriteriaQueryq = qb.create();
      Root<Customer> cust = q.from(Customer.class);
      Join<Order,Item> item = cust.join(Customer_.orders).join(Order_.lineitems);
      q.select(cust.get(Customer_.name))
      .where(qb.equal(item.get(Item_.product).get(Product_.productType),
      "printer"));
        
      Outer join with param on the join:
      SELECT c
      FROM Customer c
      LEFT JOIN c.orders o
      WHERE c.status = 1
       
      CriteriaQuery q = qb.create();
      Root<Customer> cust = q.from(Customer.class);
      Join<Customer, Order> order = cust.join(Customer_.orders, JoinType.LEFT);
      q.where(qb.equal(cust.get(Customer_.status), 1)).select(cust);
    23. Expression & criteria API (code)
      Example with ContactInfo as Embeddable class containing address and set of Phones.
       
      SELECT p.vendor
      FROM Employee e
      JOIN e.contactInfo.phones p
      WHERE e.contactInfo.address.zipcode = '95054'
       
      CriteriaQuery q = qb.create();
      Root<Employee> emp = q.from(Employee.class);
      Join<ContactInfo, Phone> phone =
      emp.join(Employee_.contactInfo).join(ContactInfo_.phones);
      q.where(qb.equal(emp.get(Employee_.contactInfo).get(
      ContactInfo_.address).get(Address_.zipcode),
      "95054")).select(phone.get(Phone_.vendor));
    24. Expression & criteria API (code)
      Example with subquery using all:SELECT emp
      FROM Employee emp
      WHERE emp.salary > ALL (SELECT m.salary
      FROM Manager m
      WHERE m.department = emp.department)
        
      // create CriteriaQuery instance, with root Employee
      CriteriaQuery q = qb.create();
      Root<Employee> emp = q.from(Employee.class);
       
      // create Subquery instance, with root Manager
      Subquery<BigDecimal> sq = q.subquery(BigDecimal.class);
      Root<Manager> manager = sq.from(Manager.class);
      sq.select(manager.get(Manager_.salary));
      sq.where(qb.equal(manager.get(Manager_.dept), emp.get(Employee_.dept)));
       
      // an all expression is applied to the subquery result
      q.select(emp).where(qb.gt(emp.get(Employee_.salary), qb.all(sq)));
    25. Expression & criteria API (code)
      Example with order by: SELECT o.quantity,
      a.zipcode
      FROM Customer c
      JOIN c.orders o
      JOIN c.address a
      WHERE a.state = 'CA’
      ORDER BY o.quantity,
      a.zipcode
      CriteriaQuery q = qb.create();
      Root<Customer> c = q.from(Customer.class);
      Join<Customer, Order> o = c.join(Customer_.orders);
      Join<Customer, Address> a = c.join(Customer_.address);
      q.where(qb.equal(a.get(Address_.state), "CA"));
      q.orderBy(qb.asc(o.get(Order_.quantity)),
      qb.asc(a.get(Address_.zipcode)));
      q.select(o.get(Order_.quantity), a.get(Address_.zipcode));
    26. Expression & criteria API (code)
      Example with group by and having:
      SELECT c.status,
      AVG(c.filledOrderCount),
      COUNT(c)
      FROM Customer c
      GROUP BY c.status
      HAVING c.status IN (1, 2)
      CriteriaQuery q = qb.create();
      Root<Customer> cust = q.from(Customer.class);
      q.groupBy(cust.get(Customer_.status));
      q.having(qb.in(cust.get(Customer_.status)).value(1).value(2));
      q.select(cust.get(Customer_.status),
      qb.avg(cust.get(Customer_.filledOrderCount)),
      qb.count(cust));
    27. AMIS Technology SchoolTrainingen & Masterclasses
      - Trainingen op vakinhoudelijke Oracle onderwerpen
      • Voor consultants, door consultants
      • Training door Oracle ACE’s en ACE Director
      • Praktijkgebaseerd
      • Professionelenazorg
      Kijk op www.amis.nlvooronsactueletrainingsaanbod
    SlideShare Zeitgeist 2009

    + Emiel PaasschensEmiel Paasschens Nominate

    custom

    857 views, 2 favs, 1 embeds more stats

    What's new in JPA 2.0

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 857
      • 856 on SlideShare
      • 1 from embeds
    • Comments 0
    • Favorites 2
    • Downloads 0
    Most viewed embeds
    • 1 views on http://jmmiddleware.wordpress.com

    more

    All embeds
    • 1 views on http://jmmiddleware.wordpress.com

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories