SlideShare uma empresa Scribd logo
1 de 62
Java Persistence API

                                  Emil Nahlik (DC Bratislava)
Copyright © 2009 Accenture All Rights Reserved.
Centra Tools
Raise Hand                 Audio/Connectivity Tips
                           •   Run the Audio Wizard
Yes / No                         •   Choose Tools/Audio Wizard from the
                                     menu at top of screen

Applause                   •   Close all network based
                               applications
                                 •   Outlook, MSN/AOL, other websites,
                                     Office Communicator, etc
Laugh
                           •   Connect via an Accenture LAN or
                               high speed internet connection
                                 •   If using a wireless connection, ensure
Text Chat                            your signal is as strong as possible

                           •   Monitor the Network Connectivity
Centra Volume Control          Bar
                                 •   Contact Learning Product Support if
                                     issues continue

Network Connectivity Bar
Asking Questions
Two Options:

    1.   Ask live questions during the designated Q&A sessions:
         •   Press Raise Hand icon to get faculty’s attention


         •    Once called upon, there are two options to speak:
              - Click the Talk button or
              - Press the Ctrl key
         When done speaking, unselect the Talk button or
         release the Ctrl Key.

    2.   Post questions at any time in the chat room.
Session structure
              • Introduction
              • Basic JPA Configuration
              • Entity relationships
              • Persistence operations and query language
              • Transactions & optimistic/pessimistic locking
              • Demo
              •Q & A


Copyright © 2009 Accenture All Rights Reserved.                 4
Introduction
 Java Persistence API (JPA) is a data persistence mechanism,
  that:

 •   is a part of JEE 5 (EJB3.0)
 •   works with Plain Old Java Objects (POJO)
 •   is DB-independent (configuration & JPA implementation)
 •   easy to use
 •   uses SQL-like language
 •   supports transactions and optimistic/pessimistic locking


Copyright © 2009 Accenture All Rights Reserved.                 5
Introduction

              There is no need to run an application
              server to use JPA. It can run as a stand
              alone, you need just a JPA implementation
              and properly configured XML file.




Copyright © 2009 Accenture All Rights Reserved.           6
Basic JPA
                                        Configuration
 What does a typical JPA project consists of?

 • JPA implementation
 • Entities
 • Entity manager
 • Configuration file – persistence.xml




Copyright © 2009 Accenture All Rights Reserved.         7
JPA Implementation
 There are many JPA implementations:
 • OpenJPA
 • Hibernate
 • TopLink
 • CocoBase
 • Castor
 • JPOX
 • etc.

Copyright © 2009 Accenture All Rights Reserved.              8
Entities
 Entity

 •    represents domain object stored in DB
 •    is a POJO class
 •    is annotated as @Entity
 •    must implement Serializable interface
 •    must have declared ID attribute

Copyright © 2009 Accenture All Rights Reserved.    9
Entities
 Example:

 @Entity
 public class Customer implements Serializable {
   private static final long serialVersionUID = 1L;

      @Id
      private Integer id;
      private String firstName;
      private String lastName;
 }



Copyright © 2009 Accenture All Rights Reserved.       10
Entities
 You can set ID (primary key) by your own


 @Entity
 public class Customer {
   @Id
   private int id = 0;
   …
 }

 Somewhere in the code:
 Customer cust = new Customer();
 cust.setId(123);

Copyright © 2009 Accenture All Rights Reserved.    11
Entities
 Or you can use Sequence to generate ID (primary key)

 • Sequence (in DB)
 • Sequence genererator (in Entity)


 @Entity
 public class Customer {
   @Id
   @SequenceGenerator(name=“Cust_Gen”,sequenceName=“Cust_Seq”)
   @GeneratedValue(generator=“Cust_Gen”)
   private int id;
   …
 }


Copyright © 2009 Accenture All Rights Reserved.                  12
Entity Manager
 Entity Manager is responsible                           for   managing
 persistence and transactions.

 • Create-Read-Update-Delete (CRUD) operations
 • Java Persistence Query Language (JPQL)
 • Access to transactions




Copyright © 2009 Accenture All Rights Reserved.                           13
Configuration file
 There is persistence.xml configuration file that contains JPA
 configuration. Inside this file, we define Persistence Unit and
 configure:

 • JPA provider class
 • Data source
 • Transaction type (JTA / non-JTA)
 • List of entity classes that are persisted by Persistence Unit
 • Additional parameters – e.g. Hibernate dialect


Copyright © 2009 Accenture All Rights Reserved.                    14
Configuration file
 <?xml version="1.0" encoding="UTF-8"?>
 <persistence version="1.0" xmlns=http://java.sun.com/xml/ns/persistence>
  <persistence-unit name=“MyPersistenceUnit" transaction-type="RESOURCE_LOCAL">
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <non-jta-data-source>TEST_DB</non-jta-data-source>
   <class>jpa.webinar.entities.Person</class>
   <class>jpa.webinar.entities.Address</class>
   <class>jpa.webinar.entities.PhoneNumber</class>

   <!-- Hibernate properties -->
   <properties>
    <property name="hibernate.dialect“
              value="org.hibernate.dialect.Oracle10gDialect"/>
    <property name="hibernate.show_sql" value="true"/>
    <property name="hibernate.format_sql" value="true"/>
   </properties>
  </persistence-unit>
 </persistence>




Copyright © 2009 Accenture All Rights Reserved.                                   15
Entities and
                                        Relationships
 There are many types of relationships:

 • 1-to-1 – unidirectional (AB) / bidirectional (AB)
 • 1-to-N – unidirectional / bidirectional
 • N-to-1 – unidirectional / bidirectional
 • M-to-N – always bidirectional




Copyright © 2009 Accenture All Rights Reserved.           16
Entities and
                                        Relationships
  Unidirectional relationship                     Bidirectional relationship
  1-to-1 (A  B)                                  1-to-N (A  B)

  ClassA a = new ClassA();                        ClassA a = new ClassA();
  ClassB b = new ClassB();                        ClassB b = new ClassB();
  a.setB(b);                                      a.addB(b);
                                                  b.setA(a);


                                                  For bidirectional relationships,
                                                  we always have to set both sides
                                                  of relationship!


Copyright © 2009 Accenture All Rights Reserved.                                      17
Entities and
                                        Relationships
 Persistence-by-reachability

 In JPA, when object is persisted, no related entities are
 persisted automatically by default.

 There are two options:
 • Call persist method for each entity separately
 • Use cascading to extend persistence reachability


Copyright © 2009 Accenture All Rights Reserved.              18
Cascading
 Persistence operation are applied to specified entities.
 Similar to cascade deletes known from PL/SQL.

 There are many types of cascades:
 • PERSIST
 • MERGE
 • REMOVE
 • REFRESH
 • ALL ( = PERSIST + MERGE + REMOVE + REFRESH)

Copyright © 2009 Accenture All Rights Reserved.             19
Cascading
 Example:

 @Entity
 public class Customer {

     @OneToOne( cascade = CascadeType.ALL )
     private IDCard idCard;

     @OneToMany(mappedBy = “custId”,
                cascade = { CascadeType.PERSIST, CascadeType.MERGE } )
     private List<Order> orders;


     // ...

 }



Copyright © 2009 Accenture All Rights Reserved.                          20
One-to-One
                                        relationship
  a) Unidirectional


                                        @OneToOne
                                        @JoinColumn(name=“address_id”)




Copyright © 2009 Accenture All Rights Reserved.                          21
One-to-One relationship
                                        (unidirectional)
  @Entity
  public class Customer implements Serializable {
    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    @OneToOne
    @JoinColumn(name=“address_id”)
    private Address address;
  }

  @Entity
  public class Address implements Serializable {
    @Id
    private Integer id;
    @Column(name=“street_name”)
    private String street;
    private String city;
  }


Copyright © 2009 Accenture All Rights Reserved.                   22
One-to-One
                                        relationship
  b) Bidirectional

                                       FK owner side (Customer):
                                       @OneToOne
                                       @JoinColumn(name=“address_id”)



                                        non-owner side (Address):
                                        @OneToOne(mappedBy=“address”)




Copyright © 2009 Accenture All Rights Reserved.                         23
One-to-One relationship
                                        (bidirectional)
  @Entity
  public class Customer implements Serializable {
    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    @OneToOne
    @JoinColumn(name=“address_id”)
    private Address address;
  }

  @Entity
  public class Address implements Serializable {
    @Id
    private Integer id;
    private String street_name;
    private String street_num;
    private String city;
    @OneToOne(mappedBy=“address”)
    private Customer cust;
  }




Copyright © 2009 Accenture All Rights Reserved.                   24
One-to-Many
                                        relationship
  • Can be unidirectional or bidirectional

  • Several data types can be used for relationship representation:
      – Collection
      – Set
      – List
      – Map

  • There are 2 ways how to define One-to-Many relationship:
      – using Foreign key
      – using Join table
Copyright © 2009 Accenture All Rights Reserved.                       25
One-to-Many
                                        relationship
  a) Using Foreign key (only Bidirectional)

                                       FK non-owner side (Customer):
                                       @OneToMany(mappedBy=“cust”)




                                        FK owner side (Phone):
                                        @ManyToOne
                                        @JoinColumn(name=“cust_id”)




Copyright © 2009 Accenture All Rights Reserved.                        26
One-to-Many relationship
                                        (foreign key)
  @Entity
  public class Customer implements Serializable {
    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    @OneToMany(mappedBy=“cust”)
    private List<Phone> phones;
  }

  @Entity
  public class Phone implements Serializable {
    @Id
    private Integer id;
    private String prefix;
    private String phoneNum;
    @ManyToOne
    @JoinColumn(name=“cust_id”)
    private Customer cust;
  }

Copyright © 2009 Accenture All Rights Reserved.                    27
One-to-Many
                                        relationship
  b) Using join table (unidirectional)

                                       Collection owner (Customer):
                                       @OneToMany
                                       @JoinTable(name=“customer_phone” …)




Copyright © 2009 Accenture All Rights Reserved.                              28
One-to-Many relationship
                                        (unidirectional)
  @Entity
  public class Customer implements Serializable {
    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    @OneToMany
    @JoinTable(name=“customer_phone”,
       joinColumns = @JoinColumn(name=“cust_id”,
       inverseJoinColumns = @JoinColumn(name=“phone_id”))
    private List<Phone> phones;
  }

  @Entity
  public class Phone implements Serializable {
    @Id
    private Integer id;
    private String prefix;
    private String phonenum;
  }

Copyright © 2009 Accenture All Rights Reserved.                    29
One-to-Many
                                        relationship
  c) Using join table (bidirectional)

                                       Collection owner (Customer):
                                       @OneToMany(mappedBy=“cust”)
                                       @JoinTable(name=“customer_phone” …)



                                        FK owner side (Phone):
                                        @ManyToOne




Copyright © 2009 Accenture All Rights Reserved.                              30
One-to-Many relationship
                                        (bidirectional)
  @Entity
  public class Customer implements Serializable {
    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    @OneToMany(mappedBy=“cust”)
    @JoinTable(name=“customer_phone”,
        joinColumns = @JoinColumn(name=“cust_id”,
        inverseJoinColumns = @JoinColumn(name=“phone_id”))
    private List<Phone> phones;
  }

  @Entity
  public class Phone implements Serializable {
    @Id
    private Integer id;
    private String prefix;
    private String phonenum;
    @ManyToOne
    private Customer cust;
  }



Copyright © 2009 Accenture All Rights Reserved.                    31
Many-to-One
                                        relationship
  Using Foreign key

                                       FK owner side (Customer):
                                       @ManyToOne
                                       @JoinColumn(name=“address_id”)




Copyright © 2009 Accenture All Rights Reserved.                         32
Many-to-One
                                        relationship
  @Entity
  public class Customer implements Serializable {
    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    @ManyToOne
    @JoinColumn(name=“address_id”)
    private Address address;
  }

  @Entity
  public class Address implements Serializable {
    @Id
    private Integer id;
    private String street_name;
    private String street_num;
    private String city;
  }


Copyright © 2009 Accenture All Rights Reserved.        33
Many-to-Many
                                        relationship
  Using join table

                                       Employee:
                                       @ManyToMany
                                       @JoinTable(name=“employee_project” …)



                                        FK owner side (Address):
                                        @ManyToMany(mappedBy=“employees”)




Copyright © 2009 Accenture All Rights Reserved.                                34
Many-to-Many
                                        relationship
  @Entity
  public class Employee implements Serializable {
    @Id
    private Integer id;
    private String firstName;
    private String lastName;
    @ManyToMany
    @JoinTable(name=“employee_project”,
        joinColumns = @JoinColumn(name=“emp_id”,
        inverseJoinColumns = @JoinColumn(name=“prj_id”))
    private Collection<Project> projects;
  }

  @Entity
  public class Project implements Serializable {
    @Id
    private Integer id;
    private String name;
    private String status;
    @ManyToOne(mappedBy=“projects”)
    private Collection<Employee> employees;
  }



Copyright © 2009 Accenture All Rights Reserved.            35
Persistence operations &
                                        query language

  All operations are managed by EntityManager

  • is instantiated using EntityManager Factory
  • based on persistence unit name (persistence.xml)

  To instantiate EntityManager:
  EntityManagerFactory emf =
    Persistence.createEntityManagerFactory(“PersistenceUnit”);
  EntityManager mng = emf.createEntityManager();



Copyright © 2009 Accenture All Rights Reserved.                    36
Entity Manager –
                                        Entity lifecycle




Copyright © 2009 Accenture All Rights Reserved.            37
Entity Manager –
                                        CRUD operations
  • Create: persist(Object obj) ~ INSERT
  • Read: T find(Class<T> cls, Object id) ~ SELECT
  • Update: T merge(T t) ~ UPDATE
  • Delete: remove(Object obj) ~ DELETE




Copyright © 2009 Accenture All Rights Reserved.            38
Entity Manager –
                                        CRUD operations
  persist(Object obj)
  - persists object into DB (new records)

  Example:
  Customer cust = new Customer();
  cust.setFirstName(“John”);
  cust.setLastName(“Smith”);

  entityManager.persist(cust);




Copyright © 2009 Accenture All Rights Reserved.            39
Entity Manager –
                                        CRUD operations
  T find(Class<T> cls, Object id)
  -finds record of given in DB
  -returns instance of class cls or null

  Example:
  Integer customerId = 123;
  Class cls = Customer.class;

  Customer cust = entityManager.find(cls, customerId);




Copyright © 2009 Accenture All Rights Reserved.            40
Entity Manager –
                                        CRUD operations
  T merge(T obj)
  -to update existing record
  -returns updated Entity

  Example:
  Integer customerId = 123;
  Class cls = Customer.class;
  Customer cust = entityManager.find(cls, customerId);

  cust.setFirstName(“John jr”);
  entityManager.merge(cust);


Copyright © 2009 Accenture All Rights Reserved.            41
Entity Manager –
                                        CRUD operations
  remove(Object obj)
  - removes object from DB

  Example:
  Integer customerId = 123;
  Class cls = Customer.class;
  Customer cust = entityManager.find(cls, customerId);

  entityManager.remove(cust);




Copyright © 2009 Accenture All Rights Reserved.            42
Entity Manager –
                                        CRUD operations
  refresh(Object obj)
  - retrieves actual state of object from DB

  Example:
  Integer customerId = 123;
  Class cls = Customer.class;
  Customer cust = entityManager.find(cls, customerId);

  ...
  entityManager.refresh(cust);




Copyright © 2009 Accenture All Rights Reserved.            43
Entity Manager –
                                        CRUD operations
  Callbacks for Persistence operations:
  • @PrePersist
  • @PostPersist
  • @PostLoad
  • @PreUpdate
  • @PostUpdate
  • @PreRemove
  • @PostRemove

Copyright © 2009 Accenture All Rights Reserved.            44
Entity Manager –
                                        CRUD operations
  Callbacks for Persistence operations:

  @Entity
  @EntityListeners({CustomerListener.class})
  public class Customer {
    @Id private Integer id;

      @PreUpdate
      private void something() {
        System.out.println(“before update...”);
      }
  }


  public class CustomerListener {
    @PostUpdate
    public void postUpdate(Customer cust) {
      System.out.println(“after update...”);
    }
  }




Copyright © 2009 Accenture All Rights Reserved.            45
Entity Manager
  Queries

  • Query language similar to SQL
  • Query
  • Named Query
  • Native Query



Copyright © 2009 Accenture All Rights Reserved.          46
Entity Manager –
                                        Queries
  Query – simple query (one-time use)

  • parameters
  • wildcards % and _ are supported

  Example:
  String jql = “SELECT c FROM Customer c WHERE c.firstName LIKE ?”;
  Query query = entityManager.createQuery(jql);

  query.setParameter(1, “J%”);
  List<Customer> customers = query.getResultList();

Copyright © 2009 Accenture All Rights Reserved.                       47
Entity Manager –
                                        Queries
  Named Query – precompiled query
  @Entity
  @NamedQueries({
     @NamedQuery(
       name=“findByLastName”,
       query=“SELECT c FROM Customer c WHERE c.lastName = :lstName”)
  })
  public class Customer {
  }

  Query query = entityManager.createNamedQuery(“findByLastName”);
  query.setParameter(“lstName”, “Smith”);
  List<Customer> customers = query.getResultList();



Copyright © 2009 Accenture All Rights Reserved.                        48
Entity Manager –
                                        Queries
  Native Query
  @Entity
  @Table(name=“CUSTOMER”
  @NamedNativeQuery(name=“nativeQuery”,
    query=“SELECT c.id FROM customer c WHERE c.lastName = ?)”,
    resultClass = Customer.class)

  public class Customer {
  }

  Query query = entityManager.createNativeQuery(“nativeQ”);
  query.setParameter(1, “Smith”);
  List<Customer> customers = query.getResultList();



Copyright © 2009 Accenture All Rights Reserved.                  49
Transactions
  There are two ways to handle transactions:

  • by application (SE)
  • by JTA (EE)

  <persistence-unit name=“MyUnit" transaction-type="RESOURCE_LOCAL">
                                                  or
  <persistence-unit name=“MyUnit" transaction-type=“JTA">




Copyright © 2009 Accenture All Rights Reserved.                        50
Transactions
  EntityManger methods:

  • begin()
  • commit()
  • setRollbackOnly()
  • rollback()
  • isActive()


Copyright © 2009 Accenture All Rights Reserved.        51
Transactions
  Example:

  Transaction t = mng.getTransaction();
  try {
         t.begin();
         mng.persist(obj1);
         mng.persist(obj2);
         mng.commit();
  }
  catch (Exception e) {
    mng.setRollbackOnly(true);
  }
  finally {
    if (t.isRollbackOnly) t.rollback();
  }

Copyright © 2009 Accenture All Rights Reserved.        52
Locking
  To avoid concurrency access, two types of
  locking are available in JPA:

  • Optimistic locking
  • Pessimistic locking (JPA2.0)




Copyright © 2009 Accenture All Rights Reserved.   53
Optimistic Locking
  Checks if record has been updated by different
  transaction (right before performing operation)

  • lock() method
  • lock modes:
      – READ (OPTIMISTIC in JPA2.0)
      – WRITE (OPTIMISTIC_FORCE_INCREMENT)



Copyright © 2009 Accenture All Rights Reserved.              54
Optimistic Locking
  Example:

  @Entity
  public class Customer implements Serializable {
    ...
    @Version
    private Timestamp lastUpdateTimestamp;
  }


  try {
    Customer cust = mng.find(Customer.class, 123);
    mng.lock(cust, WRITE);  OPTIMISTIC_FORCE_INCREMENT in JPA2.0
    // some update here...
    mng.merge(cust);
    transaction.commit();
  }
  catch (OptimisticLockException e) {
    System.out.println(“Concurrent update detected!”);
  }

Copyright © 2009 Accenture All Rights Reserved.                     55
Pessimistic Locking
  Explicitly locks records in DB to avoid update by
  different transaction. Available from JPA2.0.

  • lock() method
  • lock modes:
           – PESSIMISTIC
           – PESSIMISTIC_FORCE_INCREMENT



Copyright © 2009 Accenture All Rights Reserved.               56
Pessimistic Locking
  Example 1 – Lock after read:

  ...
  Customer cust = mng.find(Customer.class, custId);
  mng.lock(cust, PESSIMISTIC);
  // some update here...
  mng.merge(cust);
  transaction.commit();
  ...

  ! Risk:
  Since we first read and lock afterwards, an OptimisticException can occur
  if another transaction updates record meanwhile.
Copyright © 2009 Accenture All Rights Reserved.                               57
Pessimistic Locking
  Example 2 – Lock during read:

  ...
  Customer cust =
    mng.find(Customer.class, custId, PESSIMISTIC);
  // some update here...
  mng.merge(cust);
  transaction.commit();
  ...

  ! Risks:
  Records are locked longer. Risk of bottlenecks and deadlocks; bad
  scalability.
Copyright © 2009 Accenture All Rights Reserved.                       58
Pessimistic Locking
  Example 3 – Read, lock and refresh:

  ...
  Customer cust = mng.find(Customer.class, custId);
  mng.refresh(cust, PESSIMISTIC);
  // some update here...
  mng.merge(cust);
  transaction.commit();
  ...

  Advantage:
  Lock is acquired only for time required for update.

Copyright © 2009 Accenture All Rights Reserved.               59
Demo




Copyright © 2009 Accenture All Rights Reserved.   60
Questions & Comments




      Two options to ask a question or add your comments to the discussion:
             Use Raise Hand and then hold down the TALK icon or press the
Copyright © 2009
              CTRL key; release when done
Accenture your question in the Chat Room
       Post All Rights

Reserved.
Thank you for
participating!

Mais conteúdo relacionado

Mais procurados

Drive your dba crazy in 3 easy steps
Drive your dba crazy in 3 easy stepsDrive your dba crazy in 3 easy steps
Drive your dba crazy in 3 easy stepsAlberto Brandolini
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...gdigugli
 
Cso gaddis java_chapter14
Cso gaddis java_chapter14Cso gaddis java_chapter14
Cso gaddis java_chapter14mlrbrown
 
Presenter manual RIA technology (specially for summer interns)
Presenter manual RIA technology (specially for summer interns)Presenter manual RIA technology (specially for summer interns)
Presenter manual RIA technology (specially for summer interns)XPERT INFOTECH
 
Spring (1)
Spring (1)Spring (1)
Spring (1)Aneega
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2Eric Nelson
 
EclipseCon 2007: Effective Use of the Eclipse Modeling Framework
EclipseCon 2007: Effective Use of the Eclipse Modeling FrameworkEclipseCon 2007: Effective Use of the Eclipse Modeling Framework
EclipseCon 2007: Effective Use of the Eclipse Modeling FrameworkDave Steinberg
 
Melbourne agile and scrum sig slides v01-00
Melbourne agile and scrum sig   slides v01-00Melbourne agile and scrum sig   slides v01-00
Melbourne agile and scrum sig slides v01-00Craig Brown
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageMario Fusco
 
Performance and Extensibility with EMF
Performance and Extensibility with EMFPerformance and Extensibility with EMF
Performance and Extensibility with EMFKenn Hussey
 

Mais procurados (20)

Drive your dba crazy in 3 easy steps
Drive your dba crazy in 3 easy stepsDrive your dba crazy in 3 easy steps
Drive your dba crazy in 3 easy steps
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...
JavaOne 2012 - CON11234 - Multi device Content Display and a Smart Use of Ann...
 
Cso gaddis java_chapter14
Cso gaddis java_chapter14Cso gaddis java_chapter14
Cso gaddis java_chapter14
 
Hibernate
HibernateHibernate
Hibernate
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Java Beans
Java BeansJava Beans
Java Beans
 
Presenter manual RIA technology (specially for summer interns)
Presenter manual RIA technology (specially for summer interns)Presenter manual RIA technology (specially for summer interns)
Presenter manual RIA technology (specially for summer interns)
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
EclipseCon 2007: Effective Use of the Eclipse Modeling Framework
EclipseCon 2007: Effective Use of the Eclipse Modeling FrameworkEclipseCon 2007: Effective Use of the Eclipse Modeling Framework
EclipseCon 2007: Effective Use of the Eclipse Modeling Framework
 
Melbourne agile and scrum sig slides v01-00
Melbourne agile and scrum sig   slides v01-00Melbourne agile and scrum sig   slides v01-00
Melbourne agile and scrum sig slides v01-00
 
Jpa
JpaJpa
Jpa
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Java beans
Java beansJava beans
Java beans
 
Java beans
Java beansJava beans
Java beans
 
Real world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same languageReal world DSL - making technical and business people speaking the same language
Real world DSL - making technical and business people speaking the same language
 
Srs
SrsSrs
Srs
 
Performance and Extensibility with EMF
Performance and Extensibility with EMFPerformance and Extensibility with EMF
Performance and Extensibility with EMF
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 

Destaque

Kodeks 2
Kodeks 2Kodeks 2
Kodeks 2Ika1000
 
иерархические структуры
иерархические структурыиерархические структуры
иерархические структурыЕлена Ключева
 
Softwares Livres para Geoinformacao: Confiaveis e Poderosos
Softwares Livres para Geoinformacao: Confiaveis e PoderososSoftwares Livres para Geoinformacao: Confiaveis e Poderosos
Softwares Livres para Geoinformacao: Confiaveis e PoderososAnderson Medeiros
 
Geotecnologias - Soluções com Softwares Livres
Geotecnologias - Soluções com Softwares LivresGeotecnologias - Soluções com Softwares Livres
Geotecnologias - Soluções com Softwares LivresAnderson Medeiros
 

Destaque (6)

Kodeks 2
Kodeks 2Kodeks 2
Kodeks 2
 
Drop
DropDrop
Drop
 
иерархические структуры
иерархические структурыиерархические структуры
иерархические структуры
 
Softwares Livres para Geoinformacao: Confiaveis e Poderosos
Softwares Livres para Geoinformacao: Confiaveis e PoderososSoftwares Livres para Geoinformacao: Confiaveis e Poderosos
Softwares Livres para Geoinformacao: Confiaveis e Poderosos
 
Geotecnologias - Soluções com Softwares Livres
Geotecnologias - Soluções com Softwares LivresGeotecnologias - Soluções com Softwares Livres
Geotecnologias - Soluções com Softwares Livres
 
Geotecnologias
GeotecnologiasGeotecnologias
Geotecnologias
 

Semelhante a En webinar jpa v2final

Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'EnterprisePyCon Italia
 
2000: Making IT Happen with J2EE
2000: Making IT Happen with J2EE2000: Making IT Happen with J2EE
2000: Making IT Happen with J2EERussell Castagnaro
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJBodedns
 
Agile comparison with requriement approaches
Agile comparison with requriement approachesAgile comparison with requriement approaches
Agile comparison with requriement approachesfungfung Chen
 
Django in enterprise world
Django in enterprise worldDjango in enterprise world
Django in enterprise worldSimone Federici
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCFAKHRUN NISHA
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Inventing the future Business Programming Language
Inventing the future  Business Programming LanguageInventing the future  Business Programming Language
Inventing the future Business Programming LanguageESUG
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...Jorge Hidalgo
 
Nimbuzz march2012
Nimbuzz march2012Nimbuzz march2012
Nimbuzz march2012nlwebperf
 
Flex 3 Deep Dive
Flex 3 Deep DiveFlex 3 Deep Dive
Flex 3 Deep DiveEffective
 
JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentationjuliasceasor
 

Semelhante a En webinar jpa v2final (20)

Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
 
2000: Making IT Happen with J2EE
2000: Making IT Happen with J2EE2000: Making IT Happen with J2EE
2000: Making IT Happen with J2EE
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJB
 
Agile comparison with requriement approaches
Agile comparison with requriement approachesAgile comparison with requriement approaches
Agile comparison with requriement approaches
 
Core java
Core javaCore java
Core java
 
Core java
Core javaCore java
Core java
 
Django in enterprise world
Django in enterprise worldDjango in enterprise world
Django in enterprise world
 
Oops
OopsOops
Oops
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Inventing the future Business Programming Language
Inventing the future  Business Programming LanguageInventing the future  Business Programming Language
Inventing the future Business Programming Language
 
40020
4002040020
40020
 
40020
4002040020
40020
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 
Nimbuzz march2012
Nimbuzz march2012Nimbuzz march2012
Nimbuzz march2012
 
Java basic
Java basicJava basic
Java basic
 
Dev381.Pp
Dev381.PpDev381.Pp
Dev381.Pp
 
Type-safe DSLs
Type-safe DSLsType-safe DSLs
Type-safe DSLs
 
Flex 3 Deep Dive
Flex 3 Deep DiveFlex 3 Deep Dive
Flex 3 Deep Dive
 
JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentation
 

Mais de alvaro alcocer sotil (20)

Clase ciencia - Huesos
Clase ciencia - HuesosClase ciencia - Huesos
Clase ciencia - Huesos
 
Rm rompecabeza
Rm rompecabezaRm rompecabeza
Rm rompecabeza
 
Locomocion en animales
Locomocion en animalesLocomocion en animales
Locomocion en animales
 
Presentacion comuniccaion
Presentacion comuniccaionPresentacion comuniccaion
Presentacion comuniccaion
 
El trabajo académico chomsky
El trabajo académico chomskyEl trabajo académico chomsky
El trabajo académico chomsky
 
[002665]
[002665][002665]
[002665]
 
Catedral de-lima-historia-nc2ba-51-pps
Catedral de-lima-historia-nc2ba-51-ppsCatedral de-lima-historia-nc2ba-51-pps
Catedral de-lima-historia-nc2ba-51-pps
 
Proceso de ventas 2013
Proceso de ventas 2013Proceso de ventas 2013
Proceso de ventas 2013
 
Royal plaza
Royal plazaRoyal plaza
Royal plaza
 
Plan de marketing
Plan de marketingPlan de marketing
Plan de marketing
 
Intercambio de publicidad
Intercambio de publicidadIntercambio de publicidad
Intercambio de publicidad
 
Producto marca
Producto   marcaProducto   marca
Producto marca
 
Plan de mk tcompleto (3)
Plan de mk tcompleto (3)Plan de mk tcompleto (3)
Plan de mk tcompleto (3)
 
La marca debe ser humana
La marca debe ser humanaLa marca debe ser humana
La marca debe ser humana
 
3º sesion la competencia
3º sesion la competencia3º sesion la competencia
3º sesion la competencia
 
2ºsesion beneficios de la planeacion de marketing
2ºsesion beneficios de la planeacion de marketing2ºsesion beneficios de la planeacion de marketing
2ºsesion beneficios de la planeacion de marketing
 
1º sesion planeamiento estratégico de marketing
1º sesion planeamiento estratégico de marketing1º sesion planeamiento estratégico de marketing
1º sesion planeamiento estratégico de marketing
 
Aprendiendo publicidad ppt final paola
Aprendiendo publicidad ppt final paolaAprendiendo publicidad ppt final paola
Aprendiendo publicidad ppt final paola
 
Agencia de publicidad la campaña publicitaria -tipos
Agencia de  publicidad   la campaña publicitaria -tiposAgencia de  publicidad   la campaña publicitaria -tipos
Agencia de publicidad la campaña publicitaria -tipos
 
10º
 10º 10º
10º
 

En webinar jpa v2final

  • 1. Java Persistence API Emil Nahlik (DC Bratislava) Copyright © 2009 Accenture All Rights Reserved.
  • 2. Centra Tools Raise Hand Audio/Connectivity Tips • Run the Audio Wizard Yes / No • Choose Tools/Audio Wizard from the menu at top of screen Applause • Close all network based applications • Outlook, MSN/AOL, other websites, Office Communicator, etc Laugh • Connect via an Accenture LAN or high speed internet connection • If using a wireless connection, ensure Text Chat your signal is as strong as possible • Monitor the Network Connectivity Centra Volume Control Bar • Contact Learning Product Support if issues continue Network Connectivity Bar
  • 3. Asking Questions Two Options: 1. Ask live questions during the designated Q&A sessions: • Press Raise Hand icon to get faculty’s attention • Once called upon, there are two options to speak: - Click the Talk button or - Press the Ctrl key When done speaking, unselect the Talk button or release the Ctrl Key. 2. Post questions at any time in the chat room.
  • 4. Session structure • Introduction • Basic JPA Configuration • Entity relationships • Persistence operations and query language • Transactions & optimistic/pessimistic locking • Demo •Q & A Copyright © 2009 Accenture All Rights Reserved. 4
  • 5. Introduction Java Persistence API (JPA) is a data persistence mechanism, that: • is a part of JEE 5 (EJB3.0) • works with Plain Old Java Objects (POJO) • is DB-independent (configuration & JPA implementation) • easy to use • uses SQL-like language • supports transactions and optimistic/pessimistic locking Copyright © 2009 Accenture All Rights Reserved. 5
  • 6. Introduction There is no need to run an application server to use JPA. It can run as a stand alone, you need just a JPA implementation and properly configured XML file. Copyright © 2009 Accenture All Rights Reserved. 6
  • 7. Basic JPA Configuration What does a typical JPA project consists of? • JPA implementation • Entities • Entity manager • Configuration file – persistence.xml Copyright © 2009 Accenture All Rights Reserved. 7
  • 8. JPA Implementation There are many JPA implementations: • OpenJPA • Hibernate • TopLink • CocoBase • Castor • JPOX • etc. Copyright © 2009 Accenture All Rights Reserved. 8
  • 9. Entities Entity • represents domain object stored in DB • is a POJO class • is annotated as @Entity • must implement Serializable interface • must have declared ID attribute Copyright © 2009 Accenture All Rights Reserved. 9
  • 10. Entities Example: @Entity public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id private Integer id; private String firstName; private String lastName; } Copyright © 2009 Accenture All Rights Reserved. 10
  • 11. Entities You can set ID (primary key) by your own @Entity public class Customer { @Id private int id = 0; … } Somewhere in the code: Customer cust = new Customer(); cust.setId(123); Copyright © 2009 Accenture All Rights Reserved. 11
  • 12. Entities Or you can use Sequence to generate ID (primary key) • Sequence (in DB) • Sequence genererator (in Entity) @Entity public class Customer { @Id @SequenceGenerator(name=“Cust_Gen”,sequenceName=“Cust_Seq”) @GeneratedValue(generator=“Cust_Gen”) private int id; … } Copyright © 2009 Accenture All Rights Reserved. 12
  • 13. Entity Manager Entity Manager is responsible for managing persistence and transactions. • Create-Read-Update-Delete (CRUD) operations • Java Persistence Query Language (JPQL) • Access to transactions Copyright © 2009 Accenture All Rights Reserved. 13
  • 14. Configuration file There is persistence.xml configuration file that contains JPA configuration. Inside this file, we define Persistence Unit and configure: • JPA provider class • Data source • Transaction type (JTA / non-JTA) • List of entity classes that are persisted by Persistence Unit • Additional parameters – e.g. Hibernate dialect Copyright © 2009 Accenture All Rights Reserved. 14
  • 15. Configuration file <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0" xmlns=http://java.sun.com/xml/ns/persistence> <persistence-unit name=“MyPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <non-jta-data-source>TEST_DB</non-jta-data-source> <class>jpa.webinar.entities.Person</class> <class>jpa.webinar.entities.Address</class> <class>jpa.webinar.entities.PhoneNumber</class> <!-- Hibernate properties --> <properties> <property name="hibernate.dialect“ value="org.hibernate.dialect.Oracle10gDialect"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence> Copyright © 2009 Accenture All Rights Reserved. 15
  • 16. Entities and Relationships There are many types of relationships: • 1-to-1 – unidirectional (AB) / bidirectional (AB) • 1-to-N – unidirectional / bidirectional • N-to-1 – unidirectional / bidirectional • M-to-N – always bidirectional Copyright © 2009 Accenture All Rights Reserved. 16
  • 17. Entities and Relationships Unidirectional relationship Bidirectional relationship 1-to-1 (A  B) 1-to-N (A  B) ClassA a = new ClassA(); ClassA a = new ClassA(); ClassB b = new ClassB(); ClassB b = new ClassB(); a.setB(b); a.addB(b); b.setA(a); For bidirectional relationships, we always have to set both sides of relationship! Copyright © 2009 Accenture All Rights Reserved. 17
  • 18. Entities and Relationships Persistence-by-reachability In JPA, when object is persisted, no related entities are persisted automatically by default. There are two options: • Call persist method for each entity separately • Use cascading to extend persistence reachability Copyright © 2009 Accenture All Rights Reserved. 18
  • 19. Cascading Persistence operation are applied to specified entities. Similar to cascade deletes known from PL/SQL. There are many types of cascades: • PERSIST • MERGE • REMOVE • REFRESH • ALL ( = PERSIST + MERGE + REMOVE + REFRESH) Copyright © 2009 Accenture All Rights Reserved. 19
  • 20. Cascading Example: @Entity public class Customer { @OneToOne( cascade = CascadeType.ALL ) private IDCard idCard; @OneToMany(mappedBy = “custId”, cascade = { CascadeType.PERSIST, CascadeType.MERGE } ) private List<Order> orders; // ... } Copyright © 2009 Accenture All Rights Reserved. 20
  • 21. One-to-One relationship a) Unidirectional @OneToOne @JoinColumn(name=“address_id”) Copyright © 2009 Accenture All Rights Reserved. 21
  • 22. One-to-One relationship (unidirectional) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToOne @JoinColumn(name=“address_id”) private Address address; } @Entity public class Address implements Serializable { @Id private Integer id; @Column(name=“street_name”) private String street; private String city; } Copyright © 2009 Accenture All Rights Reserved. 22
  • 23. One-to-One relationship b) Bidirectional FK owner side (Customer): @OneToOne @JoinColumn(name=“address_id”) non-owner side (Address): @OneToOne(mappedBy=“address”) Copyright © 2009 Accenture All Rights Reserved. 23
  • 24. One-to-One relationship (bidirectional) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToOne @JoinColumn(name=“address_id”) private Address address; } @Entity public class Address implements Serializable { @Id private Integer id; private String street_name; private String street_num; private String city; @OneToOne(mappedBy=“address”) private Customer cust; } Copyright © 2009 Accenture All Rights Reserved. 24
  • 25. One-to-Many relationship • Can be unidirectional or bidirectional • Several data types can be used for relationship representation: – Collection – Set – List – Map • There are 2 ways how to define One-to-Many relationship: – using Foreign key – using Join table Copyright © 2009 Accenture All Rights Reserved. 25
  • 26. One-to-Many relationship a) Using Foreign key (only Bidirectional) FK non-owner side (Customer): @OneToMany(mappedBy=“cust”) FK owner side (Phone): @ManyToOne @JoinColumn(name=“cust_id”) Copyright © 2009 Accenture All Rights Reserved. 26
  • 27. One-to-Many relationship (foreign key) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToMany(mappedBy=“cust”) private List<Phone> phones; } @Entity public class Phone implements Serializable { @Id private Integer id; private String prefix; private String phoneNum; @ManyToOne @JoinColumn(name=“cust_id”) private Customer cust; } Copyright © 2009 Accenture All Rights Reserved. 27
  • 28. One-to-Many relationship b) Using join table (unidirectional) Collection owner (Customer): @OneToMany @JoinTable(name=“customer_phone” …) Copyright © 2009 Accenture All Rights Reserved. 28
  • 29. One-to-Many relationship (unidirectional) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToMany @JoinTable(name=“customer_phone”, joinColumns = @JoinColumn(name=“cust_id”, inverseJoinColumns = @JoinColumn(name=“phone_id”)) private List<Phone> phones; } @Entity public class Phone implements Serializable { @Id private Integer id; private String prefix; private String phonenum; } Copyright © 2009 Accenture All Rights Reserved. 29
  • 30. One-to-Many relationship c) Using join table (bidirectional) Collection owner (Customer): @OneToMany(mappedBy=“cust”) @JoinTable(name=“customer_phone” …) FK owner side (Phone): @ManyToOne Copyright © 2009 Accenture All Rights Reserved. 30
  • 31. One-to-Many relationship (bidirectional) @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @OneToMany(mappedBy=“cust”) @JoinTable(name=“customer_phone”, joinColumns = @JoinColumn(name=“cust_id”, inverseJoinColumns = @JoinColumn(name=“phone_id”)) private List<Phone> phones; } @Entity public class Phone implements Serializable { @Id private Integer id; private String prefix; private String phonenum; @ManyToOne private Customer cust; } Copyright © 2009 Accenture All Rights Reserved. 31
  • 32. Many-to-One relationship Using Foreign key FK owner side (Customer): @ManyToOne @JoinColumn(name=“address_id”) Copyright © 2009 Accenture All Rights Reserved. 32
  • 33. Many-to-One relationship @Entity public class Customer implements Serializable { @Id private Integer id; private String firstName; private String lastName; @ManyToOne @JoinColumn(name=“address_id”) private Address address; } @Entity public class Address implements Serializable { @Id private Integer id; private String street_name; private String street_num; private String city; } Copyright © 2009 Accenture All Rights Reserved. 33
  • 34. Many-to-Many relationship Using join table Employee: @ManyToMany @JoinTable(name=“employee_project” …) FK owner side (Address): @ManyToMany(mappedBy=“employees”) Copyright © 2009 Accenture All Rights Reserved. 34
  • 35. Many-to-Many relationship @Entity public class Employee implements Serializable { @Id private Integer id; private String firstName; private String lastName; @ManyToMany @JoinTable(name=“employee_project”, joinColumns = @JoinColumn(name=“emp_id”, inverseJoinColumns = @JoinColumn(name=“prj_id”)) private Collection<Project> projects; } @Entity public class Project implements Serializable { @Id private Integer id; private String name; private String status; @ManyToOne(mappedBy=“projects”) private Collection<Employee> employees; } Copyright © 2009 Accenture All Rights Reserved. 35
  • 36. Persistence operations & query language All operations are managed by EntityManager • is instantiated using EntityManager Factory • based on persistence unit name (persistence.xml) To instantiate EntityManager: EntityManagerFactory emf = Persistence.createEntityManagerFactory(“PersistenceUnit”); EntityManager mng = emf.createEntityManager(); Copyright © 2009 Accenture All Rights Reserved. 36
  • 37. Entity Manager – Entity lifecycle Copyright © 2009 Accenture All Rights Reserved. 37
  • 38. Entity Manager – CRUD operations • Create: persist(Object obj) ~ INSERT • Read: T find(Class<T> cls, Object id) ~ SELECT • Update: T merge(T t) ~ UPDATE • Delete: remove(Object obj) ~ DELETE Copyright © 2009 Accenture All Rights Reserved. 38
  • 39. Entity Manager – CRUD operations persist(Object obj) - persists object into DB (new records) Example: Customer cust = new Customer(); cust.setFirstName(“John”); cust.setLastName(“Smith”); entityManager.persist(cust); Copyright © 2009 Accenture All Rights Reserved. 39
  • 40. Entity Manager – CRUD operations T find(Class<T> cls, Object id) -finds record of given in DB -returns instance of class cls or null Example: Integer customerId = 123; Class cls = Customer.class; Customer cust = entityManager.find(cls, customerId); Copyright © 2009 Accenture All Rights Reserved. 40
  • 41. Entity Manager – CRUD operations T merge(T obj) -to update existing record -returns updated Entity Example: Integer customerId = 123; Class cls = Customer.class; Customer cust = entityManager.find(cls, customerId); cust.setFirstName(“John jr”); entityManager.merge(cust); Copyright © 2009 Accenture All Rights Reserved. 41
  • 42. Entity Manager – CRUD operations remove(Object obj) - removes object from DB Example: Integer customerId = 123; Class cls = Customer.class; Customer cust = entityManager.find(cls, customerId); entityManager.remove(cust); Copyright © 2009 Accenture All Rights Reserved. 42
  • 43. Entity Manager – CRUD operations refresh(Object obj) - retrieves actual state of object from DB Example: Integer customerId = 123; Class cls = Customer.class; Customer cust = entityManager.find(cls, customerId); ... entityManager.refresh(cust); Copyright © 2009 Accenture All Rights Reserved. 43
  • 44. Entity Manager – CRUD operations Callbacks for Persistence operations: • @PrePersist • @PostPersist • @PostLoad • @PreUpdate • @PostUpdate • @PreRemove • @PostRemove Copyright © 2009 Accenture All Rights Reserved. 44
  • 45. Entity Manager – CRUD operations Callbacks for Persistence operations: @Entity @EntityListeners({CustomerListener.class}) public class Customer { @Id private Integer id; @PreUpdate private void something() { System.out.println(“before update...”); } } public class CustomerListener { @PostUpdate public void postUpdate(Customer cust) { System.out.println(“after update...”); } } Copyright © 2009 Accenture All Rights Reserved. 45
  • 46. Entity Manager Queries • Query language similar to SQL • Query • Named Query • Native Query Copyright © 2009 Accenture All Rights Reserved. 46
  • 47. Entity Manager – Queries Query – simple query (one-time use) • parameters • wildcards % and _ are supported Example: String jql = “SELECT c FROM Customer c WHERE c.firstName LIKE ?”; Query query = entityManager.createQuery(jql); query.setParameter(1, “J%”); List<Customer> customers = query.getResultList(); Copyright © 2009 Accenture All Rights Reserved. 47
  • 48. Entity Manager – Queries Named Query – precompiled query @Entity @NamedQueries({ @NamedQuery( name=“findByLastName”, query=“SELECT c FROM Customer c WHERE c.lastName = :lstName”) }) public class Customer { } Query query = entityManager.createNamedQuery(“findByLastName”); query.setParameter(“lstName”, “Smith”); List<Customer> customers = query.getResultList(); Copyright © 2009 Accenture All Rights Reserved. 48
  • 49. Entity Manager – Queries Native Query @Entity @Table(name=“CUSTOMER” @NamedNativeQuery(name=“nativeQuery”, query=“SELECT c.id FROM customer c WHERE c.lastName = ?)”, resultClass = Customer.class) public class Customer { } Query query = entityManager.createNativeQuery(“nativeQ”); query.setParameter(1, “Smith”); List<Customer> customers = query.getResultList(); Copyright © 2009 Accenture All Rights Reserved. 49
  • 50. Transactions There are two ways to handle transactions: • by application (SE) • by JTA (EE) <persistence-unit name=“MyUnit" transaction-type="RESOURCE_LOCAL"> or <persistence-unit name=“MyUnit" transaction-type=“JTA"> Copyright © 2009 Accenture All Rights Reserved. 50
  • 51. Transactions EntityManger methods: • begin() • commit() • setRollbackOnly() • rollback() • isActive() Copyright © 2009 Accenture All Rights Reserved. 51
  • 52. Transactions Example: Transaction t = mng.getTransaction(); try { t.begin(); mng.persist(obj1); mng.persist(obj2); mng.commit(); } catch (Exception e) { mng.setRollbackOnly(true); } finally { if (t.isRollbackOnly) t.rollback(); } Copyright © 2009 Accenture All Rights Reserved. 52
  • 53. Locking To avoid concurrency access, two types of locking are available in JPA: • Optimistic locking • Pessimistic locking (JPA2.0) Copyright © 2009 Accenture All Rights Reserved. 53
  • 54. Optimistic Locking Checks if record has been updated by different transaction (right before performing operation) • lock() method • lock modes: – READ (OPTIMISTIC in JPA2.0) – WRITE (OPTIMISTIC_FORCE_INCREMENT) Copyright © 2009 Accenture All Rights Reserved. 54
  • 55. Optimistic Locking Example: @Entity public class Customer implements Serializable { ... @Version private Timestamp lastUpdateTimestamp; } try { Customer cust = mng.find(Customer.class, 123); mng.lock(cust, WRITE);  OPTIMISTIC_FORCE_INCREMENT in JPA2.0 // some update here... mng.merge(cust); transaction.commit(); } catch (OptimisticLockException e) { System.out.println(“Concurrent update detected!”); } Copyright © 2009 Accenture All Rights Reserved. 55
  • 56. Pessimistic Locking Explicitly locks records in DB to avoid update by different transaction. Available from JPA2.0. • lock() method • lock modes: – PESSIMISTIC – PESSIMISTIC_FORCE_INCREMENT Copyright © 2009 Accenture All Rights Reserved. 56
  • 57. Pessimistic Locking Example 1 – Lock after read: ... Customer cust = mng.find(Customer.class, custId); mng.lock(cust, PESSIMISTIC); // some update here... mng.merge(cust); transaction.commit(); ... ! Risk: Since we first read and lock afterwards, an OptimisticException can occur if another transaction updates record meanwhile. Copyright © 2009 Accenture All Rights Reserved. 57
  • 58. Pessimistic Locking Example 2 – Lock during read: ... Customer cust = mng.find(Customer.class, custId, PESSIMISTIC); // some update here... mng.merge(cust); transaction.commit(); ... ! Risks: Records are locked longer. Risk of bottlenecks and deadlocks; bad scalability. Copyright © 2009 Accenture All Rights Reserved. 58
  • 59. Pessimistic Locking Example 3 – Read, lock and refresh: ... Customer cust = mng.find(Customer.class, custId); mng.refresh(cust, PESSIMISTIC); // some update here... mng.merge(cust); transaction.commit(); ... Advantage: Lock is acquired only for time required for update. Copyright © 2009 Accenture All Rights Reserved. 59
  • 60. Demo Copyright © 2009 Accenture All Rights Reserved. 60
  • 61. Questions & Comments Two options to ask a question or add your comments to the discussion:  Use Raise Hand and then hold down the TALK icon or press the Copyright © 2009 CTRL key; release when done Accenture your question in the Chat Room  Post All Rights Reserved.

Notas do Editor

  1. The Centra tools displayed on this slide are the tools you can use to interact with the participants during this session. The RAISE YOUR HAND icon is used to ask questions or make comments. Once a participant “raises their hand”, the presenter or moderator will then call on them to speak. In order to speak, you must be given a microphone. Once the microphone is granted, you can speak by holding down the control key on your keyboard. Go ahead and click this icon now. The YES/NO icons are used to answer simple yes/no or true/false questions. Please go ahead and click these icons now. Feel free to indicate APPLAUSE or LAUGHTER during the session by choosing the applicable icons. “ The CHAT icon is an important icon. It will be used to communicate with the participants as well as the presenters. Please click on it now and resize it and move to the right side of the screen to see the Centra presentation and the chat room at the same time. There are several options on how to send your Text Chat message. We will focus on selecting “ALL” in the dropdown list. “All” is an open public forum where all messages will be displayed to both participants and presenters. Please enter your location today. [Pause: wait for participants to type messages into the chat room.] “ If you experience volume issues, you can use the Centra Volume Control. We recommend setting the bar to mid point or less for optimal audio.” “ There is also a Network Connectivity Bar at the lower right hand side of your screen. Since Centra is a real-time stream over the network, it is impacted by your network connection. This bar indicates the quality of your network connection. To ensure the best experience possible, please review the listed Audio/Connectivity Tips.
  2. You have two options today to ask questions. To ask questions live and speak via VOIP you should Press the Raise Hand icon to get the faculty’s attention. Once called up, you would hold down the Talk icon or the CTRL key and then release when done. Or you can post your question into the Text Chat at any time.
  3. “ Thank you very much for your participation in the session today. I’d also like to thank our presenters for their time and expertise.” “ When you log out you’ll be taken to a session evaluation – please take a few minutes to fill it out. Your feedback is appreciated. Thanks again for joining us. Have a good day.”