SlideShare uma empresa Scribd logo
1 de 93
Baixar para ler offline
Rochester JUG: 11-Oct-2011                                                                          © Copyright 2011, Software Alchemy




                                                  Overview of JPA v2.0
                                                            (Java Persistence API)

                                                               Entities



                                                                                           Entity
                                  In Practice
                                                                                         Operations

                                                             Overview
                                                            of JPA v2.0




                                        Containers &                               Query
                                        Deployment                               Language


                                                              Bryan Basham
                                                             Software Alchemy
                                                           basham47@gmail.com
                                                http://www.linkedin.com/in/SoftwareAlchemist

Bryan Basham – Overview of JPA v2.0                                                                                              Slide 1
Rochester JUG: 11-Oct-2011                            © Copyright 2011, Software Alchemy




                                              History

      ●     Java v1.1 (1997) included JDBC
      ●     J2EE v1.2 (1999) introduced EJB Entity beans
      ●     Entity beans sucked, so others did it better
                    –    iBATIS (2001)
                    –    Hibernate (2001)
                    –    JDO (JSR 12, final in 2002)
      ●     JPA v1.0 (JSR 220) was released in 2006
      ●     JPA v2.0 (JSR 317) was released in 2009

Bryan Basham – Overview of JPA v2.0                                                Slide 2
Rochester JUG: 11-Oct-2011                           © Copyright 2011, Software Alchemy




                                      Who Needs a Standard?

      ●     JPA provides a flexible standard
      ●     Multiple, competing implementations
                    –    DataNucleus
                    –    EclipseLink
                    –    Hibernate
                    –    ObjectDB
                    –    OpenJPA



Bryan Basham – Overview of JPA v2.0                                               Slide 3
Rochester JUG: 11-Oct-2011                                                               © Copyright 2011, Software Alchemy




                                            Typical Architecture #1

                                             Your Standalone Application



                                              JPA
                                                                                        Spring
                                                                                        (optional)
                                                              Hibernate
                   EclipseLink            OpenJPA          (plus optional libs)




                                  Java Lang / JRE                                 JDK



                                              The Java Virtual Machine



Bryan Basham – Overview of JPA v2.0                                                                                   Slide 4
Rochester JUG: 11-Oct-2011                                                                   © Copyright 2011, Software Alchemy




                                                Typical Architecture #2

                                                Your Enterprise Application



                                                                  JPA
                                      Java EE                                               Spring
                    (servlets, JSP, JSF, EJB, JNDI, etc.)                                   (optional)
                                                                  Hibernate
                                                               (plus optional libs)




                                  Java Lang / JRE                                     JDK



                                                 The Java Virtual Machine



Bryan Basham – Overview of JPA v2.0                                                                                       Slide 5
Rochester JUG: 11-Oct-2011                                                                                © Copyright 2011, Software Alchemy




                                                                         Entities
                                                                 Relationships
                                                         Keys                    Inheritance

                                                Beans &                            DB Mappings
                                                Properties        Entities



                                                                                                 Entity
                                  In Practice
                                                                                               Operations

                                                                 Overview
                                                                of JPA v2.0




                                        Containers &                                  Query
                                        Deployment                                  Language




Bryan Basham – Overview of JPA v2.0                                                                                                    Slide 6
Rochester JUG: 11-Oct-2011                           © Copyright 2011, Software Alchemy




                                      Entity Classes

      ●     Any POJO, but should be a Java Bean
      ●     Class must not be final; nor methods or
            persistence instance variables
      ●     May be Serializable and be passed across
            remote calls, such as RMI
      ●     Entities may exist in a class hierarchy
      ●     Queries may be polymorphic


Bryan Basham – Overview of JPA v2.0                                               Slide 7
Rochester JUG: 11-Oct-2011                                              © Copyright 2011, Software Alchemy




                                      Entity Classes: Example
                                                                     «entity»
      import javax.persistence.Basic;                             Employee
      import javax.persistence.Entity;
                                                            firstName : String
      @Entity /** Not fully baked */                        lastName : String
                                                            age : Integer
      public class Employee {

               @Basic(optional=false)
               private String firstName;
               @Basic(optional=false)
               private String lastName;
               @Basic(optional=false)
               private Integer age;

               public String getFirstName() { return firstName; }
               public void setFirstName(String name) { this.firstName = name; }

               public String getLastName() { return lastName; }
               public void setLastName(String name) { this.lastName = name; }

               public Integer getAge() { return age; }
               public void setAge(Integer age) { this.age = age; }

      }
Bryan Basham – Overview of JPA v2.0                                                                  Slide 8
Rochester JUG: 11-Oct-2011                         © Copyright 2011, Software Alchemy




                                      Access Types

      ●     Access to DB fields can be on instance
            variables or properties
      ●     You can specific the access type with an
            annotation:
      @Entity
      @Access(AccessType.PROPERTY)
      public class Employee { /* entity code */ }

      ●     If no access type is defined, then the default
            type (by usage) applies to the whole entity
            class hierarchy

Bryan Basham – Overview of JPA v2.0                                             Slide 9
Rochester JUG: 11-Oct-2011                                          © Copyright 2011, Software Alchemy




                                      Entity Classes: Example #2

      // assume all necessary imports from now on

      @Entity
      @Access(AccessType.PROPERTY)
      public class Employee {

               private String _firstName;
               private String _lastName;
               private Integer _age;

               @Basic(optional=false)
               public String getFirstName() { return _firstName; }
               public void setFirstName(String name) { this._firstName = name; }

               @Basic(optional=false)
               public String getLastName() { return _lastName; }
               public void setLastName(String name) { this._lastName = name; }

               @Basic(optional=false)
               public Integer getAge() { return _age; }
               public void setAge(Integer age) { this._age = age; }


Bryan Basham – Overview of JPA v2.0                                                             Slide 10
Rochester JUG: 11-Oct-2011                               © Copyright 2011, Software Alchemy




                                              Data Types

      ●     A property data type can be:
                    –    any Java primitive
                    –    any Java primitive wrapper
                    –    Strings
                    –    Dates
                    –    Big integer and decimals
                    –    Byte arrays (for BLOBs)
                    –    Character arrays (for CLOBs)
                    –    Enum values
Bryan Basham – Overview of JPA v2.0                                                  Slide 11
Rochester JUG: 11-Oct-2011                                                © Copyright 2011, Software Alchemy




                                            Enum Types
                                                  «entity»
                                                                             «enumeratedType»
                                                 Employee
                                                                                     Gender
                                           gender : Gender
                                           firstName : String               +MALE
                                           lastName : String                +FEMALE
      @Entity                              age : Integer
      public class Employee {

               public enum Gender { MALE, FEMALE }

               @Basic(optional = false)                      Enum ordinal
               private Gender gender;

               @Basic(optional=false)
               private String firstName;

               @Basic(optional=false)
               private String lastName;

               @Basic(optional=false)
               private Integer age;



Bryan Basham – Overview of JPA v2.0                                                                   Slide 12
Rochester JUG: 11-Oct-2011                                        © Copyright 2011, Software Alchemy




                                      Derived Properties
                                                                   «entity»
  @Entity                                                         Employee
  public class Employee {                                   firstName : String
                                                            lastName : String
           @Basic(optional=false)                           dateOfBirth : Date
           private String firstName;                        #age : Integer

           @Basic(optional=false)
           private String lastName;

           @Basic(optional=false)
           private Date dateOfBirth;

           @Transient
           private Integer age;

           public Integer getAge() {
               if ( this.age == null ) {
                   this.age = DateUtils.dateDiffYears(new Date(), this.dateOfBirth);
               }
               return age;
           }


Bryan Basham – Overview of JPA v2.0                                                           Slide 13
Rochester JUG: 11-Oct-2011                           © Copyright 2011, Software Alchemy




                                      Embeddable Properties

      ●     Useful for representing small, non-entity
            classes
      ●     Thus supports DDD Value Object concepts
            (well, almost)
      ●     Also supports Composition without the need for
            cascading deletes (fields are embedded within
            the owning entity table)
      ●     One Embeddable can embed other
            Embeddables

Bryan Basham – Overview of JPA v2.0                                              Slide 14
Rochester JUG: 11-Oct-2011                                    © Copyright 2011, Software Alchemy




                                      Embeddable Properties (2)

@Embeddable
public class PhoneNumber {

        @Basic(optional=false)
        private String areaCode; // unfortunately, can't make these final
        @Basic(optional=false)
        private String localNumber;
        @Basic(optional=true)
        private String extension;

        public PhoneNumber() {
            /* no-arg ctor for JPA */
        }
        public PhoneNumber(String areaCode, String localNumber, String extension) {
            this.areaCode = areaCode;
            this.localNumber = localNumber;
            this.extension = extension;
        }

        public String getAreaCode()    { return areaCode; }
        public String getLocalNumber() { return localNumber; }
        public String getExtension()   { return extension; }
}
Bryan Basham – Overview of JPA v2.0                                                         Slide 15
Rochester JUG: 11-Oct-2011                                                         © Copyright 2011, Software Alchemy




                                      Embeddable Properties (3)
                        «entity»                    1        «valueObject»
                     Employee             officePhone       PhoneNumber
      firstName : String                                areaCode : String
      lastName : String                                 localNumber : String
      dateOfBirth : Date                                extension : String
      #age : Integer
      officePhone : PhoneNumber




  @Entity
  public class Employee {
                                                          Fields of the Embeddable
           @Embedded                                      are embedded directly into
           private PhoneNumber officePhone;               the table of the owning Entity.




Bryan Basham – Overview of JPA v2.0                                                                            Slide 16
Rochester JUG: 11-Oct-2011                                                            © Copyright 2011, Software Alchemy




                                      Embeddable Properties (4)
                        «entity»                           1        «valueObject»
                                        type
                     Employee                                      PhoneNumber
      firstName : String                                       areaCode : String
      lastName : String                                        localNumber : String
      dateOfBirth : Date                                       extension : String
      #age : Integer                           Entity FK                                                   Map key
      phones : Map<String,
                   PhoneNumber>




  @Entity
  public class Employee {                                                Due to the one-to-many
                                                                         the embeddables are stored
           @Embedded                                                     in a separate table.
           @ElementCollection(fetch = FetchType.LAZY)
           private Map<String,PhoneNumber> phones
                   = new HashMap<String,PhoneNumber>();
Bryan Basham – Overview of JPA v2.0                                                                               Slide 17
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                            Entity Keys

      ●     Every entity must have a primary key
      ●     Key is specified with the @Id annotation
      ●     Only one key defined for a given entity class
            hierarchy
      ●     Keys can be simple or composite
      ●     Simple key (or properties of a composite key)
            must have a simple data type:
                    –    Strings, Java primitives (or wrappers), dates, or
                           big numbers
Bryan Basham – Overview of JPA v2.0                                                        Slide 18
Rochester JUG: 11-Oct-2011                                       © Copyright 2011, Software Alchemy




                                      Entity Keys: Example
                                                                  «entity»
      @Entity                                                    Employee
      public class Employee {
                                                           SSN : String
               @Id @Basic(optional=false)                  firstName : String
               // SSN must be unique (not a good choice)   lastName : String
               private String SSN;                         dateOfBirth : Date
                                                           #age : Integer
               @Basic(optional=false)
               private String firstName;

               @Basic(optional=false)
               private String lastName;

               @Basic(optional=false)
               private Date dateOfBirth;

               @Transient
               private Integer age;




Bryan Basham – Overview of JPA v2.0                                                          Slide 19
Rochester JUG: 11-Oct-2011                                             © Copyright 2011, Software Alchemy




                                      Entity Keys: Example #2
                                                                        «entity»
      @Entity
                                                                       Employee
      public class Employee {
                                                                 id : Long
               @Id @GeneratedValue                               firstName : String
               // let the DBMS assign the key on insert          lastName : String
               private Long id;                                  dateOfBirth : Date
                                                                 #age : Integer
               @Basic(optional=false)
               private String firstName;   MySQL uses autoincrement
                                           for key generation.
               @Basic(optional=false)
               private String lastName;

               @Basic(optional=false)
               private Date dateOfBirth;

               @Transient
               private Integer age;




Bryan Basham – Overview of JPA v2.0                                                                Slide 20
Rochester JUG: 11-Oct-2011                         © Copyright 2011, Software Alchemy




                                      Associations

      ●     Entities can be associated to other Entities and
            Embeddable objects
      ●     Collections (bags), sets, sorted sets, lists, and
            even maps
      ●     One-to-one, one-to-many, many-to-one, and
            many-to-many
      ●     Uni- and bi-directional relationships
      ●     Lazy and Eager fetching techniques

Bryan Basham – Overview of JPA v2.0                                            Slide 21
Rochester JUG: 11-Oct-2011                                               © Copyright 2011, Software Alchemy




                                              One-to-One

                               «entity»   1              1          «entity»
                                User              employee         Employee
               id : Long                                     id : Long
               userName : String                             firstName : String
               password : String                             lastName : String
               employee : Employee                           dateOfBirth : Date
                                                             #age : Integer


      @Entity
      public class User {

               @Id @GeneratedValue    private Long id;
               @Basic(optional=false) private String userName;
               @Basic(optional=false) private String password;

               @Basic(optional=false)
               @OneToOne(fetch=FetchType.EAGER)
               private Employee employee;




Bryan Basham – Overview of JPA v2.0                                                                  Slide 22
Rochester JUG: 11-Oct-2011                                             © Copyright 2011, Software Alchemy




                                            One-to-One (2)
      private void createExampleUser() {
          Calendar cal = Calendar.getInstance();
          try {
              em.getTransaction().begin();

                       Employee emp = new Employee();
                       emp.setGender(Gender.MALE);
                       emp.setFirstName("Bryan");
                       emp.setLastName("Basham");
                       cal.set(1964, 7, 22);
                       emp.setDateOfBirth(cal.getTime());
                       em.persist(emp); // NOTE: need to persist all entities
                       User u1 = new User();
                       u1.setUserName("bbasham");
                       u1.setPassword("guess");
                       u1.setEmployee(emp);
                       em.persist(u1);

                   em.getTransaction().commit();
               } catch (Exception e) {
                   e.printStackTrace();
                   em.getTransaction().rollback();
               }
      }
Bryan Basham – Overview of JPA v2.0                                                                Slide 23
Rochester JUG: 11-Oct-2011                                              © Copyright 2011, Software Alchemy




                                              One-to-Many

                               «entity»   1          0..*          «entity»
                          Department                staff         Employee
               id : Long                                    id : Long
               name : String                                firstName : String
               staff : Set<Employee>                        lastName : String
                                                            dateOfBirth : Date
                                                            #age : Integer


      @Entity
      public class Department {

               @Id @GeneratedValue
               private Long id;

               @Basic(optional = false)
               private String name;

               @OneToMany(fetch = FetchType.LAZY)
               private Set<Employee> staff;




Bryan Basham – Overview of JPA v2.0                                                                 Slide 24
Rochester JUG: 11-Oct-2011                                               © Copyright 2011, Software Alchemy




                                                 Many-to-Many



                               «entity»   0..*       0..*           «entity»
                               Project    projects   team          Employee
              id : Long                                     id : Long
              name : String                                 firstName : String
              team : Set<Employee>                          lastName : String
                                                            dateOfBirth : Date
                                                            #age : Integer
                                                            projects : Set<Project>




Bryan Basham – Overview of JPA v2.0                                                                  Slide 25
Rochester JUG: 11-Oct-2011                                                       © Copyright 2011, Software Alchemy




                                      Many-to-Many (2)
      @Entity
      public class Project {

              @Id @GeneratedValue
              private Long id;

              @Basic(optional = false)
              private String name;

              @ManyToMany(fetch = FetchType.LAZY)
              private Set<Employee> team;


      @Entity
                                             The mappedTo value
      public class Employee {
                                             specifies that the Project entity
                                             is the “owner” of the relationship.
              @Id @GeneratedValue
              private Long id;

              // Skipping basic properties

              @ManyToMany(fetch = FetchType.LAZY, mappedTo=”team”)
              private Set<Project> projects;

Bryan Basham – Overview of JPA v2.0                                                                          Slide 26
Rochester JUG: 11-Oct-2011                                       © Copyright 2011, Software Alchemy




                                                   Many-to-Many (3)


                                      Project FK     Employee FK




Bryan Basham – Overview of JPA v2.0                                                          Slide 27
Rochester JUG: 11-Oct-2011                                         © Copyright 2011, Software Alchemy




                                              Inheritance

      ●     JPA supports flexible Entity inheritance
      ●     A Entity may be an abstract class
      ●     An Entity class can extend a non-Entity class
      ●     A non-Entity class can extend an Entity class
      ●     Queries can be written to any Entity classes
      ●     Three DB mapping strategies:
                    –    SINGLE_TABLE   (the default)
                    –    JOINED
                    –    TABLE_PER_CLASS   (not required per spec)
Bryan Basham – Overview of JPA v2.0                                                            Slide 28
Rochester JUG: 11-Oct-2011                                                                  © Copyright 2011, Software Alchemy




                                                    Inheritance Example

                                                    «entity»
                                      1          AbstractGame
                                  game1
                                             id : Long
                                      1      team1Score : int
                                  game2      team2Score : int

                                             getTeam1() : Team
                                                                                  «entity»
                                             getTeam2() : Team
                                             getWinner() : Team                       Team




                                                                                  1


                                                                                               1
                                                                                                   team2
                                                                                      team1
                                  «entity»                            «entity»
                       IntermediateGame                            StartingTeam
                  game1 : AbstractGame                         team1 : Team
                  game2 : AbstractGame                         team2 : Team


Bryan Basham – Overview of JPA v2.0                                                                                     Slide 29
Rochester JUG: 11-Oct-2011                                   © Copyright 2011, Software Alchemy




                                      Single Table Example
      @Entity
      @Inheritance(strategy=InheritanceType.SINGLE_TABLE)
      @DiscriminatorColumn( name="game_type" )
      public abstract class AbstractGame {
          @Id @GeneratedValue    private Long id;
          @Basic(optional=false) private Integer team1Score;
          @Basic(optional=false) private Integer team2Score;


      @Entity
      @DiscriminatorValue("SG")
      public class StartingGame extends AbstractGame {
          @Basic(optional=false) private Team team1;
          @Basic(optional=false) private Team team2;


      @Entity
      @DiscriminatorValue("IG")
      public class IntermediateGame extends AbstractGame {
          @Basic(optional=false) private AbstractGame game1;
          @Basic(optional=false) private AbstractGame game2;



Bryan Basham – Overview of JPA v2.0                                                      Slide 30
Rochester JUG: 11-Oct-2011                                                          © Copyright 2011, Software Alchemy




                                             Single Table Example (2)
                                             AbstractGame              IntermediateGame




                             discriminator                  StartingGame
                                 field
Bryan Basham – Overview of JPA v2.0                                                                             Slide 31
Rochester JUG: 11-Oct-2011                                   © Copyright 2011, Software Alchemy




                                      Joined Example
      @Entity
      @Inheritance(strategy=InheritanceType.JOINED)
      public abstract class AbstractGame {
          @Id @GeneratedValue    private Long id;
          @Basic(optional=false) private Integer team1Score;
          @Basic(optional=false) private Integer team2Score;


      @Entity
      public class StartingGame extends AbstractGame {
          @Basic(optional=false) private Team team1;
          @Basic(optional=false) private Team team2;


      @Entity
      public class IntermediateGame extends AbstractGame {
          @Basic(optional=false) private AbstractGame game1;
          @Basic(optional=false) private AbstractGame game2;




Bryan Basham – Overview of JPA v2.0                                                      Slide 32
Rochester JUG: 11-Oct-2011                                                © Copyright 2011, Software Alchemy




                                              Joined Example (2)
                               AbstractGame                     IntermediateGame




                                                 StartingGame


Bryan Basham – Overview of JPA v2.0                                                                   Slide 33
Rochester JUG: 11-Oct-2011                             © Copyright 2011, Software Alchemy




                                       Database Mappings

      ●     JPA implementations like Hibernate can
            dynamically create a DB schema for RAD
      ●     But if you have an existing schema, then you
            can use annotations to map:
                    –    Entity classes to tables
                    –    Entity properties to fields
                    –    Join columns of relationships
                    –    ...and more


Bryan Basham – Overview of JPA v2.0                                                Slide 34
Rochester JUG: 11-Oct-2011                                                                   © Copyright 2011, Software Alchemy




                                                      Domain Model Example
                                                               «entity»
                                                             Department
                                                       id : Long
                                                       name : String
                                                       staff : Set<Employee>
                                                                1    department


                                                             0..*    staff

          «entity»                     1          1            «entity»                  1         «valueObject»
                                                                                  type
           User                            employee          Employee                            PhoneNumber
id : Long                                             firstName : String                     areaCode : String
userName : String                                     lastName : String                      localNumber : String
password : String                                     dateOfBirth : Date                     extension : String
employee : Employee                                   #age : Integer
                                                      phones : Map<>
                                                      projects : Set<Project>
                                                      user : User
                                                      department : Department
                                                             0..*    team

                                                              0..*   projects

                                                               «entity»
                                                               Project
                                                       id : Long
                                                       name : String
 Bryan Basham – Overview of JPA v2.0                   team : Set<Employee>                                               Slide 35
Rochester JUG: 11-Oct-2011                                            © Copyright 2011, Software Alchemy




                                                 ER Diagram
             «table»                             «table»                 «table»
              USR                                EMP                      DEPT
SID           :   BIGINT(20)          SID        :   BIGINT(20)     SID : BIGINT(20)
NAME          :   VARCHAR(32)         FNAME      :   VARCHAR(100)   NAME : VARCHAR(64)
PW            :   VARCHAR(16)         LNAME      :   VARCHAR(100)
EMP_SID       :   NUMBER(20)          DOB        :   DATETIME
                                      GEN_CODE   :   VARCHAR(6)




                                                                               «table»
                                                 «table»
                                                                         EMP_PHONE
                                            PRJ_EMP
                                                                    EMP_SID        :   BIGINT(20)
                                      PRJ_SID : BIGINT(20)          TYPE           :   VARCHAR(7)
                                      EMP_SID : BIGINT(20)          AREA_CODE      :   CHAR(3)
                                                                    NUMBER         :   CHAR(4)
                                                                    EXT            :   CHAR(3)



                                                 «table»
                                                  PRJ
                                      SID : BIGINT(20)
Bryan Basham – Overview of JPA v2.0   NAME : VARCHAR(64)                                          Slide 36
Rochester JUG: 11-Oct-2011                         © Copyright 2011, Software Alchemy




                                      Basic DB Mappings

      @Entity
      @Table(name="EMP")
      public class Employee {

               @Id @GeneratedValue
               @Column(name="SID")
               private Long id;

               @Basic(optional = false)
               @Column(name="GEN_CODE", length=6)
               @Enumerated(value=EnumType.STRING)
               private Gender gender;

               @Basic(optional=false)
               @Column(name="FNAME", length=100)
               private String firstName;

               @Basic(optional=false)
               @Column(name="LNAME", length=100)
               private String lastName;



Bryan Basham – Overview of JPA v2.0                                            Slide 37
Rochester JUG: 11-Oct-2011                                          © Copyright 2011, Software Alchemy




                                      Relationship Mappings

      @Entity
      @Table(name="USR")
      public class User {

               @Id @GeneratedValue
               @Column(name="SID")
               private Long id

               @Basic(optional = false)
               @Column(name="NAME", length=32, unique=true)
               private String userName;

               @Basic(optional = false)
               @Column(name="PW", length=16)
               private String password;

               @Basic(optional = false)
               @OneToOne(fetch = FetchType.EAGER, cascade={CascadeType.ALL})
               @JoinColumn(name="EMP_SID")
               private Employee employee;



Bryan Basham – Overview of JPA v2.0                                                             Slide 38
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                      Relationship Mappings (2)

      @Entity
      @Table(name = "PRJ")
      public class Project {

               @Id
               @GeneratedValue
               @Column(name = "SID")
               private Long id;

               @Basic(optional = false)
               @Column(name = "NAME", length=64)
               private String name;

          @ManyToMany(fetch = FetchType.EAGER)
          @JoinTable(name = "PRJ_EMP",
                  joinColumns = { @JoinColumn(name = "PRJ_SID",
      referencedColumnName = "SID") },
                  inverseJoinColumns = { @JoinColumn(name = "EMP_SID",
      referencedColumnName = "SID") })
          private Set<Employee> team = new HashSet<Employee>();



Bryan Basham – Overview of JPA v2.0                                                        Slide 39
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                      Embeddable Mappings

      @Entity
      @Table(name="EMP")
      public class Employee {
          @Embedded
          @ElementCollection(fetch = FetchType.LAZY)
          @CollectionTable(name="EMP_PHONE",
                  joinColumns={ @JoinColumn(name="EMP_SID",
      referencedColumnName="SID") })
          @MapKeyColumn(name="PHONE_TYPE")
          private Map<String, PhoneNumber> phones = new HashMap<String,
      PhoneNumber>();



      @Embeddable
      public class PhoneNumber {
          @Column(name="AREA_CODE", length=3)
          private String areaCode;
          @Column(name="NUMBER", length=7)
          private String localNumber;
          @Column(name="AREA_CODE", length=3, nullable=true)
          private String areaCode;

Bryan Basham – Overview of JPA v2.0                                                        Slide 40
Rochester JUG: 11-Oct-2011                                                                                © Copyright 2011, Software Alchemy




                                                            Entity Operations
                                                                Relationships
                                                        Keys                    Inheritance

                                               Beans &                            DB Mappings
                                               Properties        Entities

                                                                                        EntityManager
                                                                                                           CRUD Ops

                                                                                                Entity
                                 In Practice
                                                                                              Operations

                                                                                                 Other operations
                                                                Overview
                                                               of JPA v2.0




                                       Containers &                                  Query
                                       Deployment                                  Language




Bryan Basham – Overview of JPA v2.0                                                                                                   Slide 41
Rochester JUG: 11-Oct-2011                                                                  © Copyright 2011, Software Alchemy




                                                      Entity Manager
                        «class»
                   Persistence
            {from javax.persistence}

 createEntityManager-
   Factory(String puName) : EMF



                                                       «interface»
                                                 EntityManagerFactory
                                                 {from javax.persistence}

                                              createEntityManager() : EM



                                      ....
                                      ..                                              «interface»
                                      .....
                                      ....                                         EntityManager
                 META-INF/persistence.xml                                       {from javax.persistence}

                                                                        persist(entity:Object) : void
                                                                        find(eCls:Class<T>, key:Object) : T
                                                                        merge(entity:T) : T
                                                                        remove(entity:Object)

Bryan Basham – Overview of JPA v2.0                                                                                     Slide 42
Rochester JUG: 11-Oct-2011                                           © Copyright 2011, Software Alchemy




                                          CRUD Operations

      ●     Create:
                    –    Just create an Entity POJO with no id
                    –    Call em.persist(entity); JPA populates id
      ●     Retrieve:
                    –    Employee emp = em.find(Employee.class, 47L);
      ●     Update:
                    –    Create POJO with id; call em.merge(entity)
      ●     Delete:
                    –    Create POJO with id; call em.remove(entity)

Bryan Basham – Overview of JPA v2.0                                                              Slide 43
Rochester JUG: 11-Oct-2011                              © Copyright 2011, Software Alchemy




                                      Persisting Relationships

      ●     By default, you must persist all parts by hand
                    –    Remember our example:
      // Make and persist an employee
      Employee emp = new Employee(); // setters skipped
      em.persist(emp);
      // Make and persist a user
      User user = new User(); // setters skipped
      user.setEmployee(emp);
      em.persist(user);

      ●     You can tell JPA to persist parts with many
            relationship annotations



Bryan Basham – Overview of JPA v2.0                                                 Slide 44
Rochester JUG: 11-Oct-2011                                          © Copyright 2011, Software Alchemy




                                      Cascading Operations
      @Entity
      public class User {

               @Id @GeneratedValue    private Long id;
               @Basic(optional=false) private String userName;
               @Basic(optional=false) private String password;

               @Basic(optional=false)
               @OneToOne(fetch=FetchType.EAGER , cascade={CascadeType.ALL})
               private Employee employee;


      private void createExampleUser() {
              em.getTransaction().begin();
              // Make an employee
              Employee emp = new Employee(); // setters skipped
              // Make a user
              User user = new User(); // setters skipped
              user.setEmployee(emp);
              // Persist the User and the Employee is automatically saved
              em.persist(user);



Bryan Basham – Overview of JPA v2.0                                                             Slide 45
Rochester JUG: 11-Oct-2011                                      © Copyright 2011, Software Alchemy




                                      Other EM Operations

      ●     flush()
                    –    Saves EM context state to DB
      ●     detach(entity)
                    –    Detaches an Entity from EM context
      ●     refresh(entity)
                    –    Refreshes the Entity state from the DB
      ●     getReference(id):T
                    –    Retrieves a lazy Entity from the DB

Bryan Basham – Overview of JPA v2.0                                                         Slide 46
Rochester JUG: 11-Oct-2011                                                                                © Copyright 2011, Software Alchemy




                                                            Query Language
                                                                Relationships
                                                        Keys                    Inheritance

                                               Beans &                            DB Mappings
                                               Properties        Entities

                                                                                        EntityManager
                                                                                                           CRUD Ops

                                                                                                Entity
                                 In Practice
                                                                                              Operations

                                                                                                 Other operations
                                                                Overview
                                                               of JPA v2.0

                                                                                              SELECT
                                                                                                        Query
                                                                                                        Parameters

                                       Containers &                                  Query                 Expressions
                                       Deployment                                  Language
                                                                                                            Joins


                                                                                UPDATE &          SELECT Clause
                                                                                DELETE



Bryan Basham – Overview of JPA v2.0                                                                                                   Slide 47
Rochester JUG: 11-Oct-2011                                      © Copyright 2011, Software Alchemy




                                      SELECT Statements

   ●     Like SQL SELECT statements; except it selects
         a whole Entity object
   ●     Examples:
                  –    SELECT e FROM Employee AS e
                  –    SELECT e FROM Employee AS e
                                JOIN e.projects p
                           WHERE p.name = 'Cobia'
   ●     Code:
         String statement = "SELECT e FROM Employee AS e";
         TypedQuery<Employee> query = em.createQuery(statement, Employee.class);
         List<Employee> list = query.getResultList();


Bryan Basham – Overview of JPA v2.0                                                         Slide 48
Rochester JUG: 11-Oct-2011                                   © Copyright 2011, Software Alchemy




                                      Query Parameters

   ●     Supports JDBC-like indexed parameters:
   private List<Employee> queryTeam(Project project) {
       String statement = "SELECT e FROM Employee AS e JOIN e.projects p WHERE
   p.name=?";
       TypedQuery<Employee> query = em.createQuery(statement, Employee.class);
       query.setParameter(1, project.getName());
       return query.getResultList();
   }

   ●     Also supports named parameters:
   private List<Employee> queryTeam(Project project) {
       String statement = "SELECT e FROM Employee AS e JOIN e.projects p WHERE
   p.name=:PRJ";
       TypedQuery<Employee> query = em.createQuery(statement, Employee.class);
       query.setParameter("PRJ", project.getName());
       return query.getResultList();
   }



Bryan Basham – Overview of JPA v2.0                                                      Slide 49
Rochester JUG: 11-Oct-2011                             © Copyright 2011, Software Alchemy




                                      Conditional Expressions

      ●     Literals
      ●     Functions
      ●     Basic Operators
      ●     Collection Operators
      ●     Path expressions




Bryan Basham – Overview of JPA v2.0                                                Slide 50
Rochester JUG: 11-Oct-2011                                   © Copyright 2011, Software Alchemy




                                              Literals

      ●     Strings: 'string' and 'string''s'
      ●     Boolean: TRUE and FALSE
      ●     Numbers: both Java and SQL literals
      ●     Dates: {d '2011-10-11'}
                    –    This syntax is handled by the JDBC provider
                    –    The JPA provider is not required to mediate
      ●     Enums: org.basham.TestJPA.entities.Gender.MALE
                    –    Probably best to just pass in as a parameter

Bryan Basham – Overview of JPA v2.0                                                      Slide 51
Rochester JUG: 11-Oct-2011                      © Copyright 2011, Software Alchemy




                                      Functions

      ●     Strings: CONCAT, SUBSTRING, TRIM, UPPER,
            LOWER, LENGTH, LOCATE
      ●     Numeric: ABS, SQRT, MOD, SIZE(collection),
            INDEX(item in a List)
      ●     Temporal: CURRENT_DATE, CURRENT_TIME,
            and CURRENT_TIMESTAMP
      ●     CASE statement
      ●     Entity Type: TYPE(game) = StartingGame

Bryan Basham – Overview of JPA v2.0                                         Slide 52
Rochester JUG: 11-Oct-2011                            © Copyright 2011, Software Alchemy




                                      Basic Operators

      ●     Comparison: <, <=, =, <>, >, >=
      ●     Arithmetic: +, -, *, /
      ●     Logical: NOT, AND, and OR
      ●     Between: x [NOT] BETWEEN y AND z
      ●     String matching: x [NOT] LIKE 'B%'
      ●     Null check: x IS [NOT] NULL



Bryan Basham – Overview of JPA v2.0                                               Slide 53
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                      Collection Operators

      ●     Fixed membership:
                    –    a [NOT] IN (x, y, z, ...)
      ●     Empty:
                    –    collection IS [NOT] EMPTY
      ●     Flexible membership:
                    –    entity [NOT] MEMBER [OF] collection
      private List<Employee> queryTeam(Project project) {
          String st = "SELECT e FROM Employee e WHERE :PRJ MEMBER OF e.projects";
          TypedQuery<Employee> query = em.createQuery(st, Employee.class);
          query.setParameter("PRJ", project);
          return query.getResultList();
      }

Bryan Basham – Overview of JPA v2.0                                                        Slide 54
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                       Path Expressions

      ●     Allows simple object navigation
                    –    OneToOne and ManyToOne relationships
                    –    Single Embedded properties (no collections)
      ●     Examples:
                    –    How many Employees with short passwords?
      SELECT count(e) FROM Employee e WHERE LENGTH(e.user.password) <= 4

                    –    How many Employees with office phones in
                          Rochester?
      SELECT count(e) FROM Employee e WHERE e.officePhone.areaCode = '585'



Bryan Basham – Overview of JPA v2.0                                                        Slide 55
Rochester JUG: 11-Oct-2011                        © Copyright 2011, Software Alchemy




                                      Joins

      ●     Like SQL joins; natural for relationship traversal
      ●     Support for outer join
      ●     Support for so-called “FETCH JOIN” which
            allows the query to specify a Lazy relationship
            to be pre-fetched.




Bryan Basham – Overview of JPA v2.0                                           Slide 56
Rochester JUG: 11-Oct-2011                          © Copyright 2011, Software Alchemy




                                      Join Examples

      ●     Get Employees for a specific project and
            gender:
      SELECT e FROM Employee AS e
               JOIN e.projects p
       WHERE p.name=:N AND e.gender=:SEX

      ●     Get Projects with team members from a
            specific Department:
      SELECT p FROM Project p
               JOIN p.team emp
               JOIN emp.department dept
       WHERE dept.name=:DEPT




Bryan Basham – Overview of JPA v2.0                                             Slide 57
Rochester JUG: 11-Oct-2011                                © Copyright 2011, Software Alchemy




                                         SELECT Clause

      ●     Select Entity objects (most of what we've seen)
                    –    The result is an Entity object
      ●     Select specific attributes (like SQL)
                    –    The result is an Object[] result
      ●     Select aggregations (like SQL)
                    –    May use a GROUP BY clause
      ●     May construct new Entities from a query
      ●     May use DISTINCT; like in SQL

Bryan Basham – Overview of JPA v2.0                                                   Slide 58
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                      Aggregation Example

      ●     Department stats: # of Emps and youngest age
          private void queryEmployeeStatsByDept(Department dept) {
              String statement = "SELECT COUNT(e), MAX(e.dateOfBirth) FROM
      Employee e JOIN e.department dept WHERE dept.name=:DEPT";
              Query query = em.createQuery(statement);
              query.setParameter("DEPT", dept.getName());
              Object[] tuple = (Object[]) query.getSingleResult();
              Long numOfEmps = (Long) tuple[0];
              Date minDOB = (Date) tuple[1];
              System.out.println(String.format("There %d employees in the %s
      department with the youngest age of %d years.",
                      numOfEmps, dept.getName(), DateUtils.dateDiffYears(new
      Date(), minDOB)));
          }

      There 5 employees in the IT department with the youngest age of 20
      years.




Bryan Basham – Overview of JPA v2.0                                                        Slide 59
Rochester JUG: 11-Oct-2011                                          © Copyright 2011, Software Alchemy




                                            GROUP BY Example

      ●     List # of Emps by Department and Gender
      private void queryDepartmentStats() {
          String statement = "SELECT dept.name, emp.gender, COUNT(emp) FROM
      Employee emp JOIN emp.department dept GROUP BY dept.name, emp.gender";
          Query query = em.createQuery(statement);
          List<Object[]> list = (List<Object[]>) query.getResultList();
          System.out.println("Department stats:");
          for ( Object[] tuple : list ) {
             String deptName = (String) tuple[0];
             Gender gender = (Gender) tuple[1];
             Long numOfEmps = (Long) tuple[2];
             System.out.println("t" + deptName + " & " + gender.name() + " :
      " + numOfEmps + " employees");
          }
      }

      Department stats:
          Exec & FEMALE               : 1 employees
          Exec & MALE :               5 employees
          HR & FEMALE :               1 employees
          HR & MALE : 6               employees   ... and so on ...
Bryan Basham – Overview of JPA v2.0                                                             Slide 60
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                      UPDATE and DELETE

      ●     JPA also allows bulk updates and deletes
      ●     Syntax:
                    –    UPDATE Entity AS e
                           SET e.prop1=val1, e.prop2=val2, ...
                           WHERE e.property = ?
                    –    DELETE FROM Entity AS e
                           WHERE e.property = ?




Bryan Basham – Overview of JPA v2.0                                                        Slide 61
Rochester JUG: 11-Oct-2011                                          © Copyright 2011, Software Alchemy




                                         UPDATE Example

               private void resetPasswordsByDept(Department dept, String newPW) {
                   try {
                       em.getTransaction().begin();

                  String statement = "UPDATE User u SET u.password=? WHERE
      u.employee.id IN (SELECT e.id FROM Employee e WHERE e.department=?)";
                  Query query = em.createQuery(statement);
                  query.setParameter(1, newPW);
                  query.setParameter(2, dept);
                  int howMany = query.executeUpdate();
                  System.out.println(String.format("%d user's passwords reset
      for %s", howMany, dept));

                           em.getTransaction().commit();
                       } catch (Exception e) {
                           e.printStackTrace();
                           em.getTransaction().rollback();
                       }
               }




Bryan Basham – Overview of JPA v2.0                                                             Slide 62
Rochester JUG: 11-Oct-2011                                                                                       © Copyright 2011, Software Alchemy




                                                Containers & Deployment
                                                                        Relationships
                                                             Keys                       Inheritance

                                                    Beans &                               DB Mappings
                                                    Properties           Entities

                                                                                                EntityManager
                                                                                                                   CRUD Ops

                                                                                                        Entity
                                      In Practice
                                                                                                      Operations

                                                                                                         Other operations
                                                                     Overview
                                                                    of JPA v2.0

                                                                                                      SELECT
                                                                                                                Query
                                                                                                                Parameters

                                            Containers &                                     Query                 Expressions
                                            Deployment                                     Language
                                                                                                                    Joins


                            Packaging
                                                          Persistence                   UPDATE &          SELECT Clause
                                                          Unit                          DELETE



Bryan Basham – Overview of JPA v2.0                                                                                                          Slide 63
Rochester JUG: 11-Oct-2011                                    © Copyright 2011, Software Alchemy




                                        Persistence Unit

      ●     JPA's configuration
                    –    Configuration of the persistence provider, such
                          as Hibernate
                    –    Set of entity classes; and what to exclude
                    –    Mapping configuration; if not provided by Entity
                          class annotations
      ●     Lives in the persistence.xml file
                    –    Typically in the META-INF directory of a JAR
                    –    Or in the WEB-INF/classes directory of a WAR

Bryan Basham – Overview of JPA v2.0                                                       Slide 64
Rochester JUG: 11-Oct-2011                                          © Copyright 2011, Software Alchemy




                                      Persistence Unit (2)

      <?xml version="1.0" encoding="UTF-8"?>
      <persistence xmlns="http://java.sun.com/xml/ns/persistence"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
      http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
          version="2.0">

               <persistence-unit name="unit1" transaction-type="RESOURCE_LOCAL">
                  <!-- details -->
               </persistence-unit>

               <persistence-unit name="unit2" transaction-type="RESOURCE_LOCAL">
                  <!-- details -->
               </persistence-unit>

      </persistence>

      // code...
      EntityManagerFactory emf
          = Persistence.createEntityManagerFactory("unit1");
      EntityManager em = emf.createEntityManager();
      em.persist(entity);

Bryan Basham – Overview of JPA v2.0                                                             Slide 65
Rochester JUG: 11-Oct-2011                                           © Copyright 2011, Software Alchemy




                                      Persistence Unit (3)

      <persistence ...>

        <persistence-unit name="unit1" transaction-type="RESOURCE_LOCAL">
            <provider>org.hibernate.ejb.HibernatePersistence</provider>
            <class>org.basham.TestJPA.mappings.Employee</class>
Entity      <class>org.basham.TestJPA.mappings.User</class>
            <class>org.basham.TestJPA.mappings.Department</class>
Classes     <class>org.basham.TestJPA.mappings.Project</class>
            <exclude-unlisted-classes />
            <properties>
                <property name="hibernate.hbm2ddl.auto" value="create-drop"     Persistence
                                                                               />
                <property name="hibernate.show_sql" value="true" />              Provider
                <property name="hibernate.cache.provider_class"                configuration
   value="org.hibernate.cache.HashtableCacheProvider" />
                <property name="hibernate.dialect"
   value="org.hibernate.dialect.MySQLDialect" />
                <property name="hibernate.connection.url"
   value="jdbc:mysql://localhost:8889/TestJPA_mappings" />
                <property name="hibernate.connection.driver_class"
   value="com.mysql.jdbc.Driver" />
                <property name="hibernate.connection.password" value="root"    />
                <property name="hibernate.connection.username" value="root"    />
            </properties>
        </persistence-unit>

      </persistence>
Bryan Basham – Overview of JPA v2.0                                                              Slide 66
Rochester JUG: 11-Oct-2011                                                      © Copyright 2011, Software Alchemy




                                      Packaging a Standalone App


                                                             hibernate-jpa-2.0-api.jar



                                           hibernate-
                                           entitymanager-           jta-1.1.jar
                                           3.6.7-Final.jar



                TestJPA.jar
                                                                   JSR-305.jar

                                                                     Several other JARs

                      ....                mysql-connector-
                      ..
                      .....
                                          java-5.1.5.jar
                      ....
    META-INF/persistence.xml

Bryan Basham – Overview of JPA v2.0                                                                         Slide 67
Rochester JUG: 11-Oct-2011                                    © Copyright 2011, Software Alchemy




                                      Building a Standalone w/ Maven

      ●     If you just build a standalone JAR for your app
                    –    You must include all of the external JARs by
                          hand in the classpath during execution
                    –    Plus all of their dependencies (this gets complex)
      ●     Or you can use Maven
                    –    To manage the transitive dependencies
                    –    And build a single executable JAR




Bryan Basham – Overview of JPA v2.0                                                       Slide 68
Rochester JUG: 11-Oct-2011                                                © Copyright 2011, Software Alchemy




                                      Standalone App POM

      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="
      http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
      http://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <groupId>org.basham</groupId>
          <artifactId>TestJPA</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <packaging>jar</packaging>

             <repositories>
               <repository>
                 <id>repository.jboss.org</id>
                 <name>Public JBoss Repository Group</name>
                 <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
                 <layout>default</layout>
               </repository>
             </repositories>

             <!-- Build configuration and plugins -->

             <!-- Build dependencies -->

      </project>


Bryan Basham – Overview of JPA v2.0                                                                   Slide 69
Rochester JUG: 11-Oct-2011                                                 © Copyright 2011, Software Alchemy




                                      Standalone App POM (2)

      <project ...>

             <!-- Build configuration and plugins -->
             <build>
                 <plugins>
                      <plugin>
                          <artifactId>maven-assembly-plugin</artifactId>
                          <configuration>
                              <archive>
                                  <manifest>
                                      <mainClass>org.basham.TestJPA.app.Main</mainClass>
                                  </manifest>
                              </archive>
                              <descriptorRefs>
                                  <descriptorRef>jar-with-dependencies</descriptorRef>
                              </descriptorRefs>
                          </configuration>
                      </plugin>
                      <!-- a few other typical Maven plugins -->
                </plugins>
             </build>

      </project>




Bryan Basham – Overview of JPA v2.0                                                                    Slide 70
Rochester JUG: 11-Oct-2011                                            © Copyright 2011, Software Alchemy




                                      Standalone App POM (3)

      <project ...>

             <!-- Build dependencies -->
             <dependencies>
                 <dependency>
                     <groupId>org.hibernate</groupId>
                     <artifactId>hibernate-entitymanager</artifactId>
                     <version>3.6.7.Final</version>
                 </dependency>
                 <dependency>
                     <groupId>mysql</groupId>
                     <artifactId>mysql-connector-java</artifactId>
                     <version>5.1.12</version>
                     <scope>runtime</scope>
                 </dependency>
                 <!-- a few other dependencies -->
             </dependencies>

      </project>




Bryan Basham – Overview of JPA v2.0                                                               Slide 71
Rochester JUG: 11-Oct-2011                                                             © Copyright 2011, Software Alchemy




                                                Packing a Web App


                                                                    hibernate-jpa-2.0-api.jar




                                      WEB-INF/lib hibernate-
                                                  entitymanager-           jta-1.1.jar
                                                  3.6.7-Final.jar



            MyWebApp.war
                                                                          JSR-305.jar
                   META-INF/
                                                                            Several other JARs

                      ....                       mysql-connector-
                      ..
                      .....
                                                 java-5.1.5.jar
                      ....
             persistence.xml

Bryan Basham – Overview of JPA v2.0                                                                                Slide 72
Rochester JUG: 11-Oct-2011                          © Copyright 2011, Software Alchemy




                                      Building a Web App

      ●     Packing in a webapp is easier because all of
            the external JARs are placed in WEB-INF/lib
      ●     Again, using Maven makes this really easy




Bryan Basham – Overview of JPA v2.0                                             Slide 73
Rochester JUG: 11-Oct-2011                                                                                   © Copyright 2011, Software Alchemy




                                                                       In Practice
                                                                    Relationships
                                                         Keys                       Inheritance

                                                Beans &                               DB Mappings
                                                Properties           Entities
                        Caching
                                                                                            EntityManager
                                                                                                               CRUD Ops
        Locking
                                                                                                    Entity
                                  In Practice
                                                                                                  Operations

                                                                                                     Other operations
            Open View                                            Overview
            Pattern
                                                                of JPA v2.0
                          Partial          Paging &
                          loading          Ordering                                               SELECT
                                                                                                            Query
                                                                                                            Parameters

                                        Containers &                                     Query                 Expressions
                                        Deployment                                     Language
                                                                                                                Joins


                            Packaging
                                                      Persistence                   UPDATE &          SELECT Clause
                                                      Unit                          DELETE




Bryan Basham – Overview of JPA v2.0                                                                                                      Slide 74
Rochester JUG: 11-Oct-2011                              © Copyright 2011, Software Alchemy




                                      Paging and Ordering

      ●     The following example demonstrates the use of
            paging, searching, and ordering in a real app
      ●     This webapp, UserMgr, uses the following
            stack:
                    –    GWT and GXT (ExtJS widgets in GWT)
                    –    Spring
                    –    JPA and Spring DAO utilities
                    –    MySQL


Bryan Basham – Overview of JPA v2.0                                                 Slide 75
Rochester JUG: 11-Oct-2011                                                 © Copyright 2011, Software Alchemy




                                           UserMgr: Users Table




                                        Ordered by          Table filtered by
                                      Selected Column   UserType and Last Name

Bryan Basham – Overview of JPA v2.0                                                                    Slide 76
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                      UserMgr: Users Table (2)




                                         Table supports Paging



Bryan Basham – Overview of JPA v2.0                                                        Slide 77
Rochester JUG: 11-Oct-2011                                                                   © Copyright 2011, Software Alchemy




                                      UserMgr: User Query Stack
                                                            Server-side code


                                                                                     «helper»
                                                                               JpaDaoSupport
                                                                          {from org.spgfrm.orm.jpa.support}




    «GWT»                                 «RPC»             «service»                 «DAO»
  UserGrid                              UserRpc             UserSvc                 UserDao                       MySQL


                                           «create»                               «create»

                                                                                                     T=User
The UserGrid component on the               «valueObject»                     «valueObject»
browser sends the request for a
new page of Users via the GWT              QueryRequest                   PagedQueryResult
RPC async service which is not
shown here.                            start : int                      totalCount : int
                                       pageSize : int                   items : List<T>
                                       sortField : “String”
                                       sortDir : {ASC, DESC}


Bryan Basham – Overview of JPA v2.0                                                                                      Slide 78
Rochester JUG: 11-Oct-2011                                               © Copyright 2011, Software Alchemy




                                      UserMgr: UserDaoImpl
               public PagedQueryResult<User> retrieveUsers(final UserType userType,
                       final QueryRequest requestInfo) {
                   // Count the number of Users in this user type
                   int totalCount = getJdbcTemplate().queryForInt(
                           "SELECT count(*) FROM user WHERE user_type_id = ?",
                           new Object[] { userType.getId() });

                       // Create the dynamic query (set the ORDER BY field)
                       String sortField = requestInfo.getSortField();
  Paging               SortDir sortDir = requestInfo.getSortDirection();
  results              final String queryString = String.format(                  Order-by
                               "SELECT u FROM User u"                             criteria
                             + " WHERE u.userType = ? and u.deleted = false "
                             + " ORDER BY u.%s %s", // eg) " ORDER BY u.lastName ASC"
                               sortField, sortDir.name());

                       // Perform the query
                       // SEE NEXT SLIDE

                       return new PagedQueryResult<User>(totalCount, users);
               }



Bryan Basham – Overview of JPA v2.0                                                                  Slide 79
Rochester JUG: 11-Oct-2011                                              © Copyright 2011, Software Alchemy




                                      UserMgr: UserDaoImpl (2)
               public PagedQueryResult<User> retrieveUsers(final UserType userType,
                       final QueryRequest requestInfo) {
                   final String queryString = // SEE PREVIOUS SLIDE

                       // Perform the query
                       List<User> users = (List<User>) getJpaTemplate().executeFind(
                               new JpaCallback() {
                                   public Object doInJpa(EntityManager em)
                                           throws PersistenceException {
  Paging                               Query query = em.createQuery(queryString);
  criteria                             query.setParameter(1, userType);
                                       query.setMaxResults(requestInfo.getPageSize());
                                       query.setFirstResult(requestInfo.getStart());
                                       return query.getResultList();
                                   }
                               });

                       return new PagedQueryResult<User>(totalCount, users);
               }




Bryan Basham – Overview of JPA v2.0                                                                 Slide 80
Rochester JUG: 11-Oct-2011                                          © Copyright 2011, Software Alchemy




                                                    Partial Loading

      ●     Associations can have a FetchType of either:
                    –    LAZY : Fetch when requested (aka “lazy loaded”)
                                 ●    One-to-Many
                                 ●    Many-to-Many
                    –    Or EAGER : Fetch when Entity is retrieved
                                 ●    One-to-One
                                 ●    Many-to-One
      ●     Properties can also be lazy loaded
                    –    Default is eager

Bryan Basham – Overview of JPA v2.0                                                             Slide 81
Rochester JUG: 11-Oct-2011                                                  © Copyright 2011, Software Alchemy




                                        Partial Loading Poor Example
                                                  1      1..*
                                       «entity»   type   users   «entity»
                                      UserType                    User



      @Entity
      @Table(name="USR_TYP")
      public class UserType {
                                                                            What's wrong with
                                                                            this relationship?
               @Id @GeneratedValue
               @Column(name="SID")                                          It depends...
               private Long id;

               @Column(name="NAME", length=32, unique=true)
               private String name;

               @OneToMany(fetch = FetchType.EAGER)
               private Set<User> users;




Bryan Basham – Overview of JPA v2.0                                                                     Slide 82
Rochester JUG: 11-Oct-2011                                                                     © Copyright 2011, Software Alchemy




                                                  Partial Loading Solution

      ●     In the situation where there could be
            thousands of Users per UserType:
                    –    Remove the bi-directional association
                    –    Provide a Service tier method to query the Users
                          by type, possibly with paging and filtering
                                                       1
                                       «entity»        type                           «entity»
                                      UserType                                         User


                                                               «service»
                                                           UserTypeService
                                                  getUsers(Long typeId) : Set<User>
                                                  // better yet use
                                                  // paging & filtering


Bryan Basham – Overview of JPA v2.0                                                                                        Slide 83
Rochester JUG: 11-Oct-2011                                         © Copyright 2011, Software Alchemy




                                      Partial Loading Example

      @Entity
      @Table(name="USR")
      public class User {

               @Id @GeneratedValue
               @Column(name="SID")
               private Long id;
                                                                   Don't want to expose
               @Basic(optional = false)                            the user's password
               @Column(name="NAME", length=32, unique=true)        to the GUI.
               private String userName;

               @Basic(optional = false , fetch = FetchType.LAZY)
               @Column(name="PW", length=16)
               private String password;                            Also, the GUI rarely
                                                                   needs access to the
               @Basic(optional = false)                            Employee record.
               @OneToOne(fetch = FetchType.LAZY)
               @JoinColumn(name="EMP_SID")
               private Employee employee;



Bryan Basham – Overview of JPA v2.0                                                            Slide 84
Rochester JUG: 11-Oct-2011                                                                         © Copyright 2011, Software Alchemy




                                         Partial Loading Example (2)

                                                                                    Typical transaction boundary




                «GWT»                                     «RPC»              «service»               «DAO»
              UserGrid                                   UserRpc             UserSvc                UserDao

                                       u.getEmployee().getAge()                                           «create»



                                                                  «entity»               «entity»
                                                                   User                   User




                       But outside of the txn boundary                                        The User object is “managed”
                       access to the associated                                               within a transactional boundary.
                       Employee object fails:                                                 Outside that boundary the entity
                       LazyInitializationException
                                                                                              becomes “detached”.

Bryan Basham – Overview of JPA v2.0                                                                                            Slide 85
Rochester JUG: 11-Oct-2011                                                                        © Copyright 2011, Software Alchemy




                                        Open Session in View Pattern

      ●     One solution is to move the transaction
            boundary up the stack (say in Servlet filter):
                                              Transaction boundary




                                          «filter»
       «GWT»                               Open                      «RPC»              «service»               «DAO»
     UserGrid                         EntityManager              UserRpc                UserSvc               UserDao
                                       InViewFilter
                                                     u.getEmployee().getAge()



                                                                             «entity»
                                                                              User


Bryan Basham – Overview of JPA v2.0                                                                                           Slide 86
Rochester JUG: 11-Oct-2011                           © Copyright 2011, Software Alchemy




                                      Optimistic Locking

      ●     Assumed, but code support must be injected
      ●     The @Version annotation is used to flag an
            Entity attribute as the “version attribute”
                    –    @Version long version
                    –    @Version Date versionStamp
      ●     An OptimisticLockException is thrown when
            one session attempts to update the entity after
            another session has already done so


Bryan Basham – Overview of JPA v2.0                                              Slide 87
Rochester JUG: 11-Oct-2011                                     © Copyright 2011, Software Alchemy




                                      Pessimistic Locking

      ●     Can lock an individual entity:
      User user = em.find(User.class, 47L);
      em.lock(user, LockModeType.PESSIMISTIC_WRITE);
      // OR simply:
      User user = em.find(User.class, 47L, LockModeType.PESSIMISTIC_WRITE);

      ●     Can lock all entities returned by a query:
      String statement = // some limited query
      TypedQuery<User> query = em.createQuery(statement, User.class);
      query.setLockMode(LockModeType.PESSIMISTIC_READ);
      List<User> users = query.getResultList();




Bryan Basham – Overview of JPA v2.0                                                        Slide 88
Rochester JUG: 11-Oct-2011                      © Copyright 2011, Software Alchemy




                                      Caching

      ●     The JPA spec supports the use of second-level
            caching by the persistence provider.
      ●     The developer can mark Entity classes to be
            cached by the @Cacheable annotation.
      ●     Similarly the developer can mark an Entity
            class to never be cached using:
            @Cacheable(false)



Bryan Basham – Overview of JPA v2.0                                         Slide 89
Rochester JUG: 11-Oct-2011                                                         © Copyright 2011, Software Alchemy




                                       Caching Example

                                               0..*   children


                                                 «entity»           0..1
                                               Category             parent



      @Entity
      @Cacheable(true)
      public class Category {
                                                            The Category entity represents
                                                            a reflexive hierarchy that rarely
               @Id @GeneratedValue                          changes; thus is a good candidate
               private Long   id;                           for caching.


               private String title;

               @ManyToOne
               private Category parent;

               @Transient
               private Set<Category> children = new HashSet<Category>();



Bryan Basham – Overview of JPA v2.0                                                                            Slide 90
Rochester JUG: 11-Oct-2011                                                                                       © Copyright 2011, Software Alchemy




                                                                                 Q&A
                                                                        Relationships
                                                             Keys                       Inheritance

                                                    Beans &                               DB Mappings
                                                    Properties           Entities
                         Caching
                                                                                                EntityManager
                                                                                                                   CRUD Ops
         Locking
                                                                                                        Entity
                                      In Practice
                                                                                                      Operations

                                                                                                         Other operations
             Open View                                               Overview
             Pattern
                                                                    of JPA v2.0
                           Partial             Paging &
                           loading             Ordering                                               SELECT
                                                                                                                Query
                                                                                                                Parameters

                                            Containers &                                     Query                 Expressions
                                            Deployment                                     Language
                                                                                                                    Joins


                               Packaging
                                                          Persistence                   UPDATE &          SELECT Clause
                                                          Unit                          DELETE




Bryan Basham – Overview of JPA v2.0                                                                                                          Slide 91
Rochester JUG: 11-Oct-2011                                                            © Copyright 2011, Software Alchemy




                                      Ten Great Topics Not Covered
      1) Composite keys; great for mapping to an existing DB schema

      2) Primary key generation; eg) hashes or UUID

      3) Native SQL queries

      4) GROUP BY and HAVING clauses

      5) More nuances of Entity relationships

      6) More nuances to DB mappings

      7) Entity lifecycle events and listeners (could be used for data manipulation or auditing)

      8) Bean validation

      9) Programmatic query APIs

      10) Metamodel APIs




Bryan Basham – Overview of JPA v2.0                                                                               Slide 92
Rochester JUG: 11-Oct-2011                             © Copyright 2011, Software Alchemy




                                             Resources

      ●     JPA v2.0
                    –    JSR 317 (click here)
                    –    Javadocs (click here)
                    –    Tutorials (click here)
      ●     JPA Documentation
                    –    Wikipedia (click here)
                    –    Wikibooks (click here)



Bryan Basham – Overview of JPA v2.0                                                Slide 93

Mais conteúdo relacionado

Mais procurados

Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarAnimesh Sarkar
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Spring Framework
Spring FrameworkSpring Framework
Spring FrameworkNaLUG
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesVMware Tanzu
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsRakesh Waghela
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 

Mais procurados (20)

Spring boot
Spring bootSpring boot
Spring boot
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Hibernate
HibernateHibernate
Hibernate
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
Java collection
Java collectionJava collection
Java collection
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Java &amp; advanced java
Java &amp; advanced javaJava &amp; advanced java
Java &amp; advanced java
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 

Semelhante a Overview of JPA (Java Persistence API) v2.0

Java EE Technical Keynote - JavaOne India 2011
Java EE Technical Keynote - JavaOne India 2011Java EE Technical Keynote - JavaOne India 2011
Java EE Technical Keynote - JavaOne India 2011Arun Gupta
 
Florian adler minute project
Florian adler   minute projectFlorian adler   minute project
Florian adler minute projectDmitry Buzdin
 
Web Application Architecture
Web Application ArchitectureWeb Application Architecture
Web Application ArchitectureAbhishek Chikane
 
Plataforma Java EE 7: Produtividade & HTML5 - Parte 1
Plataforma Java EE 7: Produtividade & HTML5 - Parte 1Plataforma Java EE 7: Produtividade & HTML5 - Parte 1
Plataforma Java EE 7: Produtividade & HTML5 - Parte 1Bruno Borges
 
An introduction to OSGi
An introduction to OSGi An introduction to OSGi
An introduction to OSGi Andrea Chiodoni
 
Java Edge.2007.What.Is.New.In.Jsf.2
Java Edge.2007.What.Is.New.In.Jsf.2Java Edge.2007.What.Is.New.In.Jsf.2
Java Edge.2007.What.Is.New.In.Jsf.2roialdaag
 
N(i)2 technical architecture 2.0 (v1 1)
N(i)2 technical architecture 2.0 (v1 1)N(i)2 technical architecture 2.0 (v1 1)
N(i)2 technical architecture 2.0 (v1 1)kvz
 
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUGThe Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUGArun Gupta
 
J2ee and web services
J2ee and web servicesJ2ee and web services
J2ee and web servicesJauhar Amir
 
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011Arun Gupta
 
The Evolution of Java Persistence
The Evolution of Java PersistenceThe Evolution of Java Persistence
The Evolution of Java PersistenceShaun Smith
 
Sun Java EE 6 Overview
Sun Java EE 6 OverviewSun Java EE 6 Overview
Sun Java EE 6 Overviewsbobde
 
Spark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopSpark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopArun Gupta
 
Pure Ejb Within An Agile Context
Pure Ejb Within An Agile ContextPure Ejb Within An Agile Context
Pure Ejb Within An Agile ContextNoam Bunder
 
1006 Z2 Intro Complete
1006 Z2 Intro Complete1006 Z2 Intro Complete
1006 Z2 Intro CompleteHenning Blohm
 
JSF 2.2 Status at DOAG 2011
JSF 2.2 Status at DOAG 2011JSF 2.2 Status at DOAG 2011
JSF 2.2 Status at DOAG 2011Edward Burns
 
04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment WorkshopChuong Nguyen
 

Semelhante a Overview of JPA (Java Persistence API) v2.0 (20)

Java EE Technical Keynote - JavaOne India 2011
Java EE Technical Keynote - JavaOne India 2011Java EE Technical Keynote - JavaOne India 2011
Java EE Technical Keynote - JavaOne India 2011
 
Florian adler minute project
Florian adler   minute projectFlorian adler   minute project
Florian adler minute project
 
Web Application Architecture
Web Application ArchitectureWeb Application Architecture
Web Application Architecture
 
Plataforma Java EE 7: Produtividade & HTML5 - Parte 1
Plataforma Java EE 7: Produtividade & HTML5 - Parte 1Plataforma Java EE 7: Produtividade & HTML5 - Parte 1
Plataforma Java EE 7: Produtividade & HTML5 - Parte 1
 
An introduction to OSGi
An introduction to OSGi An introduction to OSGi
An introduction to OSGi
 
Java Edge.2007.What.Is.New.In.Jsf.2
Java Edge.2007.What.Is.New.In.Jsf.2Java Edge.2007.What.Is.New.In.Jsf.2
Java Edge.2007.What.Is.New.In.Jsf.2
 
N(i)2 technical architecture 2.0 (v1 1)
N(i)2 technical architecture 2.0 (v1 1)N(i)2 technical architecture 2.0 (v1 1)
N(i)2 technical architecture 2.0 (v1 1)
 
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUGThe Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
 
J2ee and web services
J2ee and web servicesJ2ee and web services
J2ee and web services
 
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
Java EE / GlassFish Strategy & Roadmap @ JavaOne 2011
 
Bok2
Bok2Bok2
Bok2
 
Sotona
SotonaSotona
Sotona
 
The Evolution of Java Persistence
The Evolution of Java PersistenceThe Evolution of Java Persistence
The Evolution of Java Persistence
 
Sun Java EE 6 Overview
Sun Java EE 6 OverviewSun Java EE 6 Overview
Sun Java EE 6 Overview
 
Spark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopSpark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 Workshop
 
Pure Ejb Within An Agile Context
Pure Ejb Within An Agile ContextPure Ejb Within An Agile Context
Pure Ejb Within An Agile Context
 
1006 Z2 Intro Complete
1006 Z2 Intro Complete1006 Z2 Intro Complete
1006 Z2 Intro Complete
 
Aag 2013
Aag 2013Aag 2013
Aag 2013
 
JSF 2.2 Status at DOAG 2011
JSF 2.2 Status at DOAG 2011JSF 2.2 Status at DOAG 2011
JSF 2.2 Status at DOAG 2011
 
04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop04.egovFrame Runtime Environment Workshop
04.egovFrame Runtime Environment Workshop
 

Último

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 

Último (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 

Overview of JPA (Java Persistence API) v2.0

  • 1. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Overview of JPA v2.0 (Java Persistence API) Entities Entity In Practice Operations Overview of JPA v2.0 Containers & Query Deployment Language Bryan Basham Software Alchemy basham47@gmail.com http://www.linkedin.com/in/SoftwareAlchemist Bryan Basham – Overview of JPA v2.0 Slide 1
  • 2. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy History ● Java v1.1 (1997) included JDBC ● J2EE v1.2 (1999) introduced EJB Entity beans ● Entity beans sucked, so others did it better – iBATIS (2001) – Hibernate (2001) – JDO (JSR 12, final in 2002) ● JPA v1.0 (JSR 220) was released in 2006 ● JPA v2.0 (JSR 317) was released in 2009 Bryan Basham – Overview of JPA v2.0 Slide 2
  • 3. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Who Needs a Standard? ● JPA provides a flexible standard ● Multiple, competing implementations – DataNucleus – EclipseLink – Hibernate – ObjectDB – OpenJPA Bryan Basham – Overview of JPA v2.0 Slide 3
  • 4. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Typical Architecture #1 Your Standalone Application JPA Spring (optional) Hibernate EclipseLink OpenJPA (plus optional libs) Java Lang / JRE JDK The Java Virtual Machine Bryan Basham – Overview of JPA v2.0 Slide 4
  • 5. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Typical Architecture #2 Your Enterprise Application JPA Java EE Spring (servlets, JSP, JSF, EJB, JNDI, etc.) (optional) Hibernate (plus optional libs) Java Lang / JRE JDK The Java Virtual Machine Bryan Basham – Overview of JPA v2.0 Slide 5
  • 6. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entities Relationships Keys Inheritance Beans & DB Mappings Properties Entities Entity In Practice Operations Overview of JPA v2.0 Containers & Query Deployment Language Bryan Basham – Overview of JPA v2.0 Slide 6
  • 7. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Classes ● Any POJO, but should be a Java Bean ● Class must not be final; nor methods or persistence instance variables ● May be Serializable and be passed across remote calls, such as RMI ● Entities may exist in a class hierarchy ● Queries may be polymorphic Bryan Basham – Overview of JPA v2.0 Slide 7
  • 8. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Classes: Example «entity» import javax.persistence.Basic; Employee import javax.persistence.Entity; firstName : String @Entity /** Not fully baked */ lastName : String age : Integer public class Employee { @Basic(optional=false) private String firstName; @Basic(optional=false) private String lastName; @Basic(optional=false) private Integer age; public String getFirstName() { return firstName; } public void setFirstName(String name) { this.firstName = name; } public String getLastName() { return lastName; } public void setLastName(String name) { this.lastName = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } Bryan Basham – Overview of JPA v2.0 Slide 8
  • 9. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Access Types ● Access to DB fields can be on instance variables or properties ● You can specific the access type with an annotation: @Entity @Access(AccessType.PROPERTY) public class Employee { /* entity code */ } ● If no access type is defined, then the default type (by usage) applies to the whole entity class hierarchy Bryan Basham – Overview of JPA v2.0 Slide 9
  • 10. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Classes: Example #2 // assume all necessary imports from now on @Entity @Access(AccessType.PROPERTY) public class Employee { private String _firstName; private String _lastName; private Integer _age; @Basic(optional=false) public String getFirstName() { return _firstName; } public void setFirstName(String name) { this._firstName = name; } @Basic(optional=false) public String getLastName() { return _lastName; } public void setLastName(String name) { this._lastName = name; } @Basic(optional=false) public Integer getAge() { return _age; } public void setAge(Integer age) { this._age = age; } Bryan Basham – Overview of JPA v2.0 Slide 10
  • 11. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Data Types ● A property data type can be: – any Java primitive – any Java primitive wrapper – Strings – Dates – Big integer and decimals – Byte arrays (for BLOBs) – Character arrays (for CLOBs) – Enum values Bryan Basham – Overview of JPA v2.0 Slide 11
  • 12. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Enum Types «entity» «enumeratedType» Employee Gender gender : Gender firstName : String +MALE lastName : String +FEMALE @Entity age : Integer public class Employee { public enum Gender { MALE, FEMALE } @Basic(optional = false) Enum ordinal private Gender gender; @Basic(optional=false) private String firstName; @Basic(optional=false) private String lastName; @Basic(optional=false) private Integer age; Bryan Basham – Overview of JPA v2.0 Slide 12
  • 13. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Derived Properties «entity» @Entity Employee public class Employee { firstName : String lastName : String @Basic(optional=false) dateOfBirth : Date private String firstName; #age : Integer @Basic(optional=false) private String lastName; @Basic(optional=false) private Date dateOfBirth; @Transient private Integer age; public Integer getAge() { if ( this.age == null ) { this.age = DateUtils.dateDiffYears(new Date(), this.dateOfBirth); } return age; } Bryan Basham – Overview of JPA v2.0 Slide 13
  • 14. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties ● Useful for representing small, non-entity classes ● Thus supports DDD Value Object concepts (well, almost) ● Also supports Composition without the need for cascading deletes (fields are embedded within the owning entity table) ● One Embeddable can embed other Embeddables Bryan Basham – Overview of JPA v2.0 Slide 14
  • 15. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties (2) @Embeddable public class PhoneNumber { @Basic(optional=false) private String areaCode; // unfortunately, can't make these final @Basic(optional=false) private String localNumber; @Basic(optional=true) private String extension; public PhoneNumber() { /* no-arg ctor for JPA */ } public PhoneNumber(String areaCode, String localNumber, String extension) { this.areaCode = areaCode; this.localNumber = localNumber; this.extension = extension; } public String getAreaCode() { return areaCode; } public String getLocalNumber() { return localNumber; } public String getExtension() { return extension; } } Bryan Basham – Overview of JPA v2.0 Slide 15
  • 16. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties (3) «entity» 1 «valueObject» Employee officePhone PhoneNumber firstName : String areaCode : String lastName : String localNumber : String dateOfBirth : Date extension : String #age : Integer officePhone : PhoneNumber @Entity public class Employee { Fields of the Embeddable @Embedded are embedded directly into private PhoneNumber officePhone; the table of the owning Entity. Bryan Basham – Overview of JPA v2.0 Slide 16
  • 17. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Properties (4) «entity» 1 «valueObject» type Employee PhoneNumber firstName : String areaCode : String lastName : String localNumber : String dateOfBirth : Date extension : String #age : Integer Entity FK Map key phones : Map<String, PhoneNumber> @Entity public class Employee { Due to the one-to-many the embeddables are stored @Embedded in a separate table. @ElementCollection(fetch = FetchType.LAZY) private Map<String,PhoneNumber> phones = new HashMap<String,PhoneNumber>(); Bryan Basham – Overview of JPA v2.0 Slide 17
  • 18. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Keys ● Every entity must have a primary key ● Key is specified with the @Id annotation ● Only one key defined for a given entity class hierarchy ● Keys can be simple or composite ● Simple key (or properties of a composite key) must have a simple data type: – Strings, Java primitives (or wrappers), dates, or big numbers Bryan Basham – Overview of JPA v2.0 Slide 18
  • 19. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Keys: Example «entity» @Entity Employee public class Employee { SSN : String @Id @Basic(optional=false) firstName : String // SSN must be unique (not a good choice) lastName : String private String SSN; dateOfBirth : Date #age : Integer @Basic(optional=false) private String firstName; @Basic(optional=false) private String lastName; @Basic(optional=false) private Date dateOfBirth; @Transient private Integer age; Bryan Basham – Overview of JPA v2.0 Slide 19
  • 20. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Keys: Example #2 «entity» @Entity Employee public class Employee { id : Long @Id @GeneratedValue firstName : String // let the DBMS assign the key on insert lastName : String private Long id; dateOfBirth : Date #age : Integer @Basic(optional=false) private String firstName; MySQL uses autoincrement for key generation. @Basic(optional=false) private String lastName; @Basic(optional=false) private Date dateOfBirth; @Transient private Integer age; Bryan Basham – Overview of JPA v2.0 Slide 20
  • 21. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Associations ● Entities can be associated to other Entities and Embeddable objects ● Collections (bags), sets, sorted sets, lists, and even maps ● One-to-one, one-to-many, many-to-one, and many-to-many ● Uni- and bi-directional relationships ● Lazy and Eager fetching techniques Bryan Basham – Overview of JPA v2.0 Slide 21
  • 22. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy One-to-One «entity» 1 1 «entity» User employee Employee id : Long id : Long userName : String firstName : String password : String lastName : String employee : Employee dateOfBirth : Date #age : Integer @Entity public class User { @Id @GeneratedValue private Long id; @Basic(optional=false) private String userName; @Basic(optional=false) private String password; @Basic(optional=false) @OneToOne(fetch=FetchType.EAGER) private Employee employee; Bryan Basham – Overview of JPA v2.0 Slide 22
  • 23. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy One-to-One (2) private void createExampleUser() { Calendar cal = Calendar.getInstance(); try { em.getTransaction().begin(); Employee emp = new Employee(); emp.setGender(Gender.MALE); emp.setFirstName("Bryan"); emp.setLastName("Basham"); cal.set(1964, 7, 22); emp.setDateOfBirth(cal.getTime()); em.persist(emp); // NOTE: need to persist all entities User u1 = new User(); u1.setUserName("bbasham"); u1.setPassword("guess"); u1.setEmployee(emp); em.persist(u1); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } } Bryan Basham – Overview of JPA v2.0 Slide 23
  • 24. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy One-to-Many «entity» 1 0..* «entity» Department staff Employee id : Long id : Long name : String firstName : String staff : Set<Employee> lastName : String dateOfBirth : Date #age : Integer @Entity public class Department { @Id @GeneratedValue private Long id; @Basic(optional = false) private String name; @OneToMany(fetch = FetchType.LAZY) private Set<Employee> staff; Bryan Basham – Overview of JPA v2.0 Slide 24
  • 25. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Many-to-Many «entity» 0..* 0..* «entity» Project projects team Employee id : Long id : Long name : String firstName : String team : Set<Employee> lastName : String dateOfBirth : Date #age : Integer projects : Set<Project> Bryan Basham – Overview of JPA v2.0 Slide 25
  • 26. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Many-to-Many (2) @Entity public class Project { @Id @GeneratedValue private Long id; @Basic(optional = false) private String name; @ManyToMany(fetch = FetchType.LAZY) private Set<Employee> team; @Entity The mappedTo value public class Employee { specifies that the Project entity is the “owner” of the relationship. @Id @GeneratedValue private Long id; // Skipping basic properties @ManyToMany(fetch = FetchType.LAZY, mappedTo=”team”) private Set<Project> projects; Bryan Basham – Overview of JPA v2.0 Slide 26
  • 27. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Many-to-Many (3) Project FK Employee FK Bryan Basham – Overview of JPA v2.0 Slide 27
  • 28. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Inheritance ● JPA supports flexible Entity inheritance ● A Entity may be an abstract class ● An Entity class can extend a non-Entity class ● A non-Entity class can extend an Entity class ● Queries can be written to any Entity classes ● Three DB mapping strategies: – SINGLE_TABLE (the default) – JOINED – TABLE_PER_CLASS (not required per spec) Bryan Basham – Overview of JPA v2.0 Slide 28
  • 29. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Inheritance Example «entity» 1 AbstractGame game1 id : Long 1 team1Score : int game2 team2Score : int getTeam1() : Team «entity» getTeam2() : Team getWinner() : Team Team 1 1 team2 team1 «entity» «entity» IntermediateGame StartingTeam game1 : AbstractGame team1 : Team game2 : AbstractGame team2 : Team Bryan Basham – Overview of JPA v2.0 Slide 29
  • 30. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Single Table Example @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn( name="game_type" ) public abstract class AbstractGame { @Id @GeneratedValue private Long id; @Basic(optional=false) private Integer team1Score; @Basic(optional=false) private Integer team2Score; @Entity @DiscriminatorValue("SG") public class StartingGame extends AbstractGame { @Basic(optional=false) private Team team1; @Basic(optional=false) private Team team2; @Entity @DiscriminatorValue("IG") public class IntermediateGame extends AbstractGame { @Basic(optional=false) private AbstractGame game1; @Basic(optional=false) private AbstractGame game2; Bryan Basham – Overview of JPA v2.0 Slide 30
  • 31. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Single Table Example (2) AbstractGame IntermediateGame discriminator StartingGame field Bryan Basham – Overview of JPA v2.0 Slide 31
  • 32. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Joined Example @Entity @Inheritance(strategy=InheritanceType.JOINED) public abstract class AbstractGame { @Id @GeneratedValue private Long id; @Basic(optional=false) private Integer team1Score; @Basic(optional=false) private Integer team2Score; @Entity public class StartingGame extends AbstractGame { @Basic(optional=false) private Team team1; @Basic(optional=false) private Team team2; @Entity public class IntermediateGame extends AbstractGame { @Basic(optional=false) private AbstractGame game1; @Basic(optional=false) private AbstractGame game2; Bryan Basham – Overview of JPA v2.0 Slide 32
  • 33. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Joined Example (2) AbstractGame IntermediateGame StartingGame Bryan Basham – Overview of JPA v2.0 Slide 33
  • 34. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Database Mappings ● JPA implementations like Hibernate can dynamically create a DB schema for RAD ● But if you have an existing schema, then you can use annotations to map: – Entity classes to tables – Entity properties to fields – Join columns of relationships – ...and more Bryan Basham – Overview of JPA v2.0 Slide 34
  • 35. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Domain Model Example «entity» Department id : Long name : String staff : Set<Employee> 1 department 0..* staff «entity» 1 1 «entity» 1 «valueObject» type User employee Employee PhoneNumber id : Long firstName : String areaCode : String userName : String lastName : String localNumber : String password : String dateOfBirth : Date extension : String employee : Employee #age : Integer phones : Map<> projects : Set<Project> user : User department : Department 0..* team 0..* projects «entity» Project id : Long name : String Bryan Basham – Overview of JPA v2.0 team : Set<Employee> Slide 35
  • 36. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy ER Diagram «table» «table» «table» USR EMP DEPT SID : BIGINT(20) SID : BIGINT(20) SID : BIGINT(20) NAME : VARCHAR(32) FNAME : VARCHAR(100) NAME : VARCHAR(64) PW : VARCHAR(16) LNAME : VARCHAR(100) EMP_SID : NUMBER(20) DOB : DATETIME GEN_CODE : VARCHAR(6) «table» «table» EMP_PHONE PRJ_EMP EMP_SID : BIGINT(20) PRJ_SID : BIGINT(20) TYPE : VARCHAR(7) EMP_SID : BIGINT(20) AREA_CODE : CHAR(3) NUMBER : CHAR(4) EXT : CHAR(3) «table» PRJ SID : BIGINT(20) Bryan Basham – Overview of JPA v2.0 NAME : VARCHAR(64) Slide 36
  • 37. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Basic DB Mappings @Entity @Table(name="EMP") public class Employee { @Id @GeneratedValue @Column(name="SID") private Long id; @Basic(optional = false) @Column(name="GEN_CODE", length=6) @Enumerated(value=EnumType.STRING) private Gender gender; @Basic(optional=false) @Column(name="FNAME", length=100) private String firstName; @Basic(optional=false) @Column(name="LNAME", length=100) private String lastName; Bryan Basham – Overview of JPA v2.0 Slide 37
  • 38. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Relationship Mappings @Entity @Table(name="USR") public class User { @Id @GeneratedValue @Column(name="SID") private Long id @Basic(optional = false) @Column(name="NAME", length=32, unique=true) private String userName; @Basic(optional = false) @Column(name="PW", length=16) private String password; @Basic(optional = false) @OneToOne(fetch = FetchType.EAGER, cascade={CascadeType.ALL}) @JoinColumn(name="EMP_SID") private Employee employee; Bryan Basham – Overview of JPA v2.0 Slide 38
  • 39. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Relationship Mappings (2) @Entity @Table(name = "PRJ") public class Project { @Id @GeneratedValue @Column(name = "SID") private Long id; @Basic(optional = false) @Column(name = "NAME", length=64) private String name; @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "PRJ_EMP", joinColumns = { @JoinColumn(name = "PRJ_SID", referencedColumnName = "SID") }, inverseJoinColumns = { @JoinColumn(name = "EMP_SID", referencedColumnName = "SID") }) private Set<Employee> team = new HashSet<Employee>(); Bryan Basham – Overview of JPA v2.0 Slide 39
  • 40. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Embeddable Mappings @Entity @Table(name="EMP") public class Employee { @Embedded @ElementCollection(fetch = FetchType.LAZY) @CollectionTable(name="EMP_PHONE", joinColumns={ @JoinColumn(name="EMP_SID", referencedColumnName="SID") }) @MapKeyColumn(name="PHONE_TYPE") private Map<String, PhoneNumber> phones = new HashMap<String, PhoneNumber>(); @Embeddable public class PhoneNumber { @Column(name="AREA_CODE", length=3) private String areaCode; @Column(name="NUMBER", length=7) private String localNumber; @Column(name="AREA_CODE", length=3, nullable=true) private String areaCode; Bryan Basham – Overview of JPA v2.0 Slide 40
  • 41. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Operations Relationships Keys Inheritance Beans & DB Mappings Properties Entities EntityManager CRUD Ops Entity In Practice Operations Other operations Overview of JPA v2.0 Containers & Query Deployment Language Bryan Basham – Overview of JPA v2.0 Slide 41
  • 42. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Entity Manager «class» Persistence {from javax.persistence} createEntityManager- Factory(String puName) : EMF «interface» EntityManagerFactory {from javax.persistence} createEntityManager() : EM .... .. «interface» ..... .... EntityManager META-INF/persistence.xml {from javax.persistence} persist(entity:Object) : void find(eCls:Class<T>, key:Object) : T merge(entity:T) : T remove(entity:Object) Bryan Basham – Overview of JPA v2.0 Slide 42
  • 43. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy CRUD Operations ● Create: – Just create an Entity POJO with no id – Call em.persist(entity); JPA populates id ● Retrieve: – Employee emp = em.find(Employee.class, 47L); ● Update: – Create POJO with id; call em.merge(entity) ● Delete: – Create POJO with id; call em.remove(entity) Bryan Basham – Overview of JPA v2.0 Slide 43
  • 44. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persisting Relationships ● By default, you must persist all parts by hand – Remember our example: // Make and persist an employee Employee emp = new Employee(); // setters skipped em.persist(emp); // Make and persist a user User user = new User(); // setters skipped user.setEmployee(emp); em.persist(user); ● You can tell JPA to persist parts with many relationship annotations Bryan Basham – Overview of JPA v2.0 Slide 44
  • 45. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Cascading Operations @Entity public class User { @Id @GeneratedValue private Long id; @Basic(optional=false) private String userName; @Basic(optional=false) private String password; @Basic(optional=false) @OneToOne(fetch=FetchType.EAGER , cascade={CascadeType.ALL}) private Employee employee; private void createExampleUser() { em.getTransaction().begin(); // Make an employee Employee emp = new Employee(); // setters skipped // Make a user User user = new User(); // setters skipped user.setEmployee(emp); // Persist the User and the Employee is automatically saved em.persist(user); Bryan Basham – Overview of JPA v2.0 Slide 45
  • 46. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Other EM Operations ● flush() – Saves EM context state to DB ● detach(entity) – Detaches an Entity from EM context ● refresh(entity) – Refreshes the Entity state from the DB ● getReference(id):T – Retrieves a lazy Entity from the DB Bryan Basham – Overview of JPA v2.0 Slide 46
  • 47. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Query Language Relationships Keys Inheritance Beans & DB Mappings Properties Entities EntityManager CRUD Ops Entity In Practice Operations Other operations Overview of JPA v2.0 SELECT Query Parameters Containers & Query Expressions Deployment Language Joins UPDATE & SELECT Clause DELETE Bryan Basham – Overview of JPA v2.0 Slide 47
  • 48. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy SELECT Statements ● Like SQL SELECT statements; except it selects a whole Entity object ● Examples: – SELECT e FROM Employee AS e – SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name = 'Cobia' ● Code: String statement = "SELECT e FROM Employee AS e"; TypedQuery<Employee> query = em.createQuery(statement, Employee.class); List<Employee> list = query.getResultList(); Bryan Basham – Overview of JPA v2.0 Slide 48
  • 49. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Query Parameters ● Supports JDBC-like indexed parameters: private List<Employee> queryTeam(Project project) { String statement = "SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name=?"; TypedQuery<Employee> query = em.createQuery(statement, Employee.class); query.setParameter(1, project.getName()); return query.getResultList(); } ● Also supports named parameters: private List<Employee> queryTeam(Project project) { String statement = "SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name=:PRJ"; TypedQuery<Employee> query = em.createQuery(statement, Employee.class); query.setParameter("PRJ", project.getName()); return query.getResultList(); } Bryan Basham – Overview of JPA v2.0 Slide 49
  • 50. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Conditional Expressions ● Literals ● Functions ● Basic Operators ● Collection Operators ● Path expressions Bryan Basham – Overview of JPA v2.0 Slide 50
  • 51. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Literals ● Strings: 'string' and 'string''s' ● Boolean: TRUE and FALSE ● Numbers: both Java and SQL literals ● Dates: {d '2011-10-11'} – This syntax is handled by the JDBC provider – The JPA provider is not required to mediate ● Enums: org.basham.TestJPA.entities.Gender.MALE – Probably best to just pass in as a parameter Bryan Basham – Overview of JPA v2.0 Slide 51
  • 52. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Functions ● Strings: CONCAT, SUBSTRING, TRIM, UPPER, LOWER, LENGTH, LOCATE ● Numeric: ABS, SQRT, MOD, SIZE(collection), INDEX(item in a List) ● Temporal: CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP ● CASE statement ● Entity Type: TYPE(game) = StartingGame Bryan Basham – Overview of JPA v2.0 Slide 52
  • 53. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Basic Operators ● Comparison: <, <=, =, <>, >, >= ● Arithmetic: +, -, *, / ● Logical: NOT, AND, and OR ● Between: x [NOT] BETWEEN y AND z ● String matching: x [NOT] LIKE 'B%' ● Null check: x IS [NOT] NULL Bryan Basham – Overview of JPA v2.0 Slide 53
  • 54. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Collection Operators ● Fixed membership: – a [NOT] IN (x, y, z, ...) ● Empty: – collection IS [NOT] EMPTY ● Flexible membership: – entity [NOT] MEMBER [OF] collection private List<Employee> queryTeam(Project project) { String st = "SELECT e FROM Employee e WHERE :PRJ MEMBER OF e.projects"; TypedQuery<Employee> query = em.createQuery(st, Employee.class); query.setParameter("PRJ", project); return query.getResultList(); } Bryan Basham – Overview of JPA v2.0 Slide 54
  • 55. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Path Expressions ● Allows simple object navigation – OneToOne and ManyToOne relationships – Single Embedded properties (no collections) ● Examples: – How many Employees with short passwords? SELECT count(e) FROM Employee e WHERE LENGTH(e.user.password) <= 4 – How many Employees with office phones in Rochester? SELECT count(e) FROM Employee e WHERE e.officePhone.areaCode = '585' Bryan Basham – Overview of JPA v2.0 Slide 55
  • 56. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Joins ● Like SQL joins; natural for relationship traversal ● Support for outer join ● Support for so-called “FETCH JOIN” which allows the query to specify a Lazy relationship to be pre-fetched. Bryan Basham – Overview of JPA v2.0 Slide 56
  • 57. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Join Examples ● Get Employees for a specific project and gender: SELECT e FROM Employee AS e JOIN e.projects p WHERE p.name=:N AND e.gender=:SEX ● Get Projects with team members from a specific Department: SELECT p FROM Project p JOIN p.team emp JOIN emp.department dept WHERE dept.name=:DEPT Bryan Basham – Overview of JPA v2.0 Slide 57
  • 58. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy SELECT Clause ● Select Entity objects (most of what we've seen) – The result is an Entity object ● Select specific attributes (like SQL) – The result is an Object[] result ● Select aggregations (like SQL) – May use a GROUP BY clause ● May construct new Entities from a query ● May use DISTINCT; like in SQL Bryan Basham – Overview of JPA v2.0 Slide 58
  • 59. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Aggregation Example ● Department stats: # of Emps and youngest age private void queryEmployeeStatsByDept(Department dept) { String statement = "SELECT COUNT(e), MAX(e.dateOfBirth) FROM Employee e JOIN e.department dept WHERE dept.name=:DEPT"; Query query = em.createQuery(statement); query.setParameter("DEPT", dept.getName()); Object[] tuple = (Object[]) query.getSingleResult(); Long numOfEmps = (Long) tuple[0]; Date minDOB = (Date) tuple[1]; System.out.println(String.format("There %d employees in the %s department with the youngest age of %d years.", numOfEmps, dept.getName(), DateUtils.dateDiffYears(new Date(), minDOB))); } There 5 employees in the IT department with the youngest age of 20 years. Bryan Basham – Overview of JPA v2.0 Slide 59
  • 60. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy GROUP BY Example ● List # of Emps by Department and Gender private void queryDepartmentStats() { String statement = "SELECT dept.name, emp.gender, COUNT(emp) FROM Employee emp JOIN emp.department dept GROUP BY dept.name, emp.gender"; Query query = em.createQuery(statement); List<Object[]> list = (List<Object[]>) query.getResultList(); System.out.println("Department stats:"); for ( Object[] tuple : list ) { String deptName = (String) tuple[0]; Gender gender = (Gender) tuple[1]; Long numOfEmps = (Long) tuple[2]; System.out.println("t" + deptName + " & " + gender.name() + " : " + numOfEmps + " employees"); } } Department stats: Exec & FEMALE : 1 employees Exec & MALE : 5 employees HR & FEMALE : 1 employees HR & MALE : 6 employees ... and so on ... Bryan Basham – Overview of JPA v2.0 Slide 60
  • 61. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UPDATE and DELETE ● JPA also allows bulk updates and deletes ● Syntax: – UPDATE Entity AS e SET e.prop1=val1, e.prop2=val2, ... WHERE e.property = ? – DELETE FROM Entity AS e WHERE e.property = ? Bryan Basham – Overview of JPA v2.0 Slide 61
  • 62. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UPDATE Example private void resetPasswordsByDept(Department dept, String newPW) { try { em.getTransaction().begin(); String statement = "UPDATE User u SET u.password=? WHERE u.employee.id IN (SELECT e.id FROM Employee e WHERE e.department=?)"; Query query = em.createQuery(statement); query.setParameter(1, newPW); query.setParameter(2, dept); int howMany = query.executeUpdate(); System.out.println(String.format("%d user's passwords reset for %s", howMany, dept)); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } } Bryan Basham – Overview of JPA v2.0 Slide 62
  • 63. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Containers & Deployment Relationships Keys Inheritance Beans & DB Mappings Properties Entities EntityManager CRUD Ops Entity In Practice Operations Other operations Overview of JPA v2.0 SELECT Query Parameters Containers & Query Expressions Deployment Language Joins Packaging Persistence UPDATE & SELECT Clause Unit DELETE Bryan Basham – Overview of JPA v2.0 Slide 63
  • 64. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persistence Unit ● JPA's configuration – Configuration of the persistence provider, such as Hibernate – Set of entity classes; and what to exclude – Mapping configuration; if not provided by Entity class annotations ● Lives in the persistence.xml file – Typically in the META-INF directory of a JAR – Or in the WEB-INF/classes directory of a WAR Bryan Basham – Overview of JPA v2.0 Slide 64
  • 65. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persistence Unit (2) <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="unit1" transaction-type="RESOURCE_LOCAL"> <!-- details --> </persistence-unit> <persistence-unit name="unit2" transaction-type="RESOURCE_LOCAL"> <!-- details --> </persistence-unit> </persistence> // code... EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit1"); EntityManager em = emf.createEntityManager(); em.persist(entity); Bryan Basham – Overview of JPA v2.0 Slide 65
  • 66. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Persistence Unit (3) <persistence ...> <persistence-unit name="unit1" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>org.basham.TestJPA.mappings.Employee</class> Entity <class>org.basham.TestJPA.mappings.User</class> <class>org.basham.TestJPA.mappings.Department</class> Classes <class>org.basham.TestJPA.mappings.Project</class> <exclude-unlisted-classes /> <properties> <property name="hibernate.hbm2ddl.auto" value="create-drop" Persistence /> <property name="hibernate.show_sql" value="true" /> Provider <property name="hibernate.cache.provider_class" configuration value="org.hibernate.cache.HashtableCacheProvider" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:8889/TestJPA_mappings" /> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.password" value="root" /> <property name="hibernate.connection.username" value="root" /> </properties> </persistence-unit> </persistence> Bryan Basham – Overview of JPA v2.0 Slide 66
  • 67. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Packaging a Standalone App hibernate-jpa-2.0-api.jar hibernate- entitymanager- jta-1.1.jar 3.6.7-Final.jar TestJPA.jar JSR-305.jar Several other JARs .... mysql-connector- .. ..... java-5.1.5.jar .... META-INF/persistence.xml Bryan Basham – Overview of JPA v2.0 Slide 67
  • 68. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Building a Standalone w/ Maven ● If you just build a standalone JAR for your app – You must include all of the external JARs by hand in the classpath during execution – Plus all of their dependencies (this gets complex) ● Or you can use Maven – To manage the transitive dependencies – And build a single executable JAR Bryan Basham – Overview of JPA v2.0 Slide 68
  • 69. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Standalone App POM <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.basham</groupId> <artifactId>TestJPA</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <repositories> <repository> <id>repository.jboss.org</id> <name>Public JBoss Repository Group</name> <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url> <layout>default</layout> </repository> </repositories> <!-- Build configuration and plugins --> <!-- Build dependencies --> </project> Bryan Basham – Overview of JPA v2.0 Slide 69
  • 70. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Standalone App POM (2) <project ...> <!-- Build configuration and plugins --> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>org.basham.TestJPA.app.Main</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> <!-- a few other typical Maven plugins --> </plugins> </build> </project> Bryan Basham – Overview of JPA v2.0 Slide 70
  • 71. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Standalone App POM (3) <project ...> <!-- Build dependencies --> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.7.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.12</version> <scope>runtime</scope> </dependency> <!-- a few other dependencies --> </dependencies> </project> Bryan Basham – Overview of JPA v2.0 Slide 71
  • 72. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Packing a Web App hibernate-jpa-2.0-api.jar WEB-INF/lib hibernate- entitymanager- jta-1.1.jar 3.6.7-Final.jar MyWebApp.war JSR-305.jar META-INF/ Several other JARs .... mysql-connector- .. ..... java-5.1.5.jar .... persistence.xml Bryan Basham – Overview of JPA v2.0 Slide 72
  • 73. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Building a Web App ● Packing in a webapp is easier because all of the external JARs are placed in WEB-INF/lib ● Again, using Maven makes this really easy Bryan Basham – Overview of JPA v2.0 Slide 73
  • 74. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy In Practice Relationships Keys Inheritance Beans & DB Mappings Properties Entities Caching EntityManager CRUD Ops Locking Entity In Practice Operations Other operations Open View Overview Pattern of JPA v2.0 Partial Paging & loading Ordering SELECT Query Parameters Containers & Query Expressions Deployment Language Joins Packaging Persistence UPDATE & SELECT Clause Unit DELETE Bryan Basham – Overview of JPA v2.0 Slide 74
  • 75. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Paging and Ordering ● The following example demonstrates the use of paging, searching, and ordering in a real app ● This webapp, UserMgr, uses the following stack: – GWT and GXT (ExtJS widgets in GWT) – Spring – JPA and Spring DAO utilities – MySQL Bryan Basham – Overview of JPA v2.0 Slide 75
  • 76. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: Users Table Ordered by Table filtered by Selected Column UserType and Last Name Bryan Basham – Overview of JPA v2.0 Slide 76
  • 77. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: Users Table (2) Table supports Paging Bryan Basham – Overview of JPA v2.0 Slide 77
  • 78. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: User Query Stack Server-side code «helper» JpaDaoSupport {from org.spgfrm.orm.jpa.support} «GWT» «RPC» «service» «DAO» UserGrid UserRpc UserSvc UserDao MySQL «create» «create» T=User The UserGrid component on the «valueObject» «valueObject» browser sends the request for a new page of Users via the GWT QueryRequest PagedQueryResult RPC async service which is not shown here. start : int totalCount : int pageSize : int items : List<T> sortField : “String” sortDir : {ASC, DESC} Bryan Basham – Overview of JPA v2.0 Slide 78
  • 79. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: UserDaoImpl public PagedQueryResult<User> retrieveUsers(final UserType userType, final QueryRequest requestInfo) { // Count the number of Users in this user type int totalCount = getJdbcTemplate().queryForInt( "SELECT count(*) FROM user WHERE user_type_id = ?", new Object[] { userType.getId() }); // Create the dynamic query (set the ORDER BY field) String sortField = requestInfo.getSortField(); Paging SortDir sortDir = requestInfo.getSortDirection(); results final String queryString = String.format( Order-by "SELECT u FROM User u" criteria + " WHERE u.userType = ? and u.deleted = false " + " ORDER BY u.%s %s", // eg) " ORDER BY u.lastName ASC" sortField, sortDir.name()); // Perform the query // SEE NEXT SLIDE return new PagedQueryResult<User>(totalCount, users); } Bryan Basham – Overview of JPA v2.0 Slide 79
  • 80. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy UserMgr: UserDaoImpl (2) public PagedQueryResult<User> retrieveUsers(final UserType userType, final QueryRequest requestInfo) { final String queryString = // SEE PREVIOUS SLIDE // Perform the query List<User> users = (List<User>) getJpaTemplate().executeFind( new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { Paging Query query = em.createQuery(queryString); criteria query.setParameter(1, userType); query.setMaxResults(requestInfo.getPageSize()); query.setFirstResult(requestInfo.getStart()); return query.getResultList(); } }); return new PagedQueryResult<User>(totalCount, users); } Bryan Basham – Overview of JPA v2.0 Slide 80
  • 81. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading ● Associations can have a FetchType of either: – LAZY : Fetch when requested (aka “lazy loaded”) ● One-to-Many ● Many-to-Many – Or EAGER : Fetch when Entity is retrieved ● One-to-One ● Many-to-One ● Properties can also be lazy loaded – Default is eager Bryan Basham – Overview of JPA v2.0 Slide 81
  • 82. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Poor Example 1 1..* «entity» type users «entity» UserType User @Entity @Table(name="USR_TYP") public class UserType { What's wrong with this relationship? @Id @GeneratedValue @Column(name="SID") It depends... private Long id; @Column(name="NAME", length=32, unique=true) private String name; @OneToMany(fetch = FetchType.EAGER) private Set<User> users; Bryan Basham – Overview of JPA v2.0 Slide 82
  • 83. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Solution ● In the situation where there could be thousands of Users per UserType: – Remove the bi-directional association – Provide a Service tier method to query the Users by type, possibly with paging and filtering 1 «entity» type «entity» UserType User «service» UserTypeService getUsers(Long typeId) : Set<User> // better yet use // paging & filtering Bryan Basham – Overview of JPA v2.0 Slide 83
  • 84. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Example @Entity @Table(name="USR") public class User { @Id @GeneratedValue @Column(name="SID") private Long id; Don't want to expose @Basic(optional = false) the user's password @Column(name="NAME", length=32, unique=true) to the GUI. private String userName; @Basic(optional = false , fetch = FetchType.LAZY) @Column(name="PW", length=16) private String password; Also, the GUI rarely needs access to the @Basic(optional = false) Employee record. @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name="EMP_SID") private Employee employee; Bryan Basham – Overview of JPA v2.0 Slide 84
  • 85. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Partial Loading Example (2) Typical transaction boundary «GWT» «RPC» «service» «DAO» UserGrid UserRpc UserSvc UserDao u.getEmployee().getAge() «create» «entity» «entity» User User But outside of the txn boundary The User object is “managed” access to the associated within a transactional boundary. Employee object fails: Outside that boundary the entity LazyInitializationException becomes “detached”. Bryan Basham – Overview of JPA v2.0 Slide 85
  • 86. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Open Session in View Pattern ● One solution is to move the transaction boundary up the stack (say in Servlet filter): Transaction boundary «filter» «GWT» Open «RPC» «service» «DAO» UserGrid EntityManager UserRpc UserSvc UserDao InViewFilter u.getEmployee().getAge() «entity» User Bryan Basham – Overview of JPA v2.0 Slide 86
  • 87. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Optimistic Locking ● Assumed, but code support must be injected ● The @Version annotation is used to flag an Entity attribute as the “version attribute” – @Version long version – @Version Date versionStamp ● An OptimisticLockException is thrown when one session attempts to update the entity after another session has already done so Bryan Basham – Overview of JPA v2.0 Slide 87
  • 88. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Pessimistic Locking ● Can lock an individual entity: User user = em.find(User.class, 47L); em.lock(user, LockModeType.PESSIMISTIC_WRITE); // OR simply: User user = em.find(User.class, 47L, LockModeType.PESSIMISTIC_WRITE); ● Can lock all entities returned by a query: String statement = // some limited query TypedQuery<User> query = em.createQuery(statement, User.class); query.setLockMode(LockModeType.PESSIMISTIC_READ); List<User> users = query.getResultList(); Bryan Basham – Overview of JPA v2.0 Slide 88
  • 89. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Caching ● The JPA spec supports the use of second-level caching by the persistence provider. ● The developer can mark Entity classes to be cached by the @Cacheable annotation. ● Similarly the developer can mark an Entity class to never be cached using: @Cacheable(false) Bryan Basham – Overview of JPA v2.0 Slide 89
  • 90. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Caching Example 0..* children «entity» 0..1 Category parent @Entity @Cacheable(true) public class Category { The Category entity represents a reflexive hierarchy that rarely @Id @GeneratedValue changes; thus is a good candidate private Long id; for caching. private String title; @ManyToOne private Category parent; @Transient private Set<Category> children = new HashSet<Category>(); Bryan Basham – Overview of JPA v2.0 Slide 90
  • 91. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Q&A Relationships Keys Inheritance Beans & DB Mappings Properties Entities Caching EntityManager CRUD Ops Locking Entity In Practice Operations Other operations Open View Overview Pattern of JPA v2.0 Partial Paging & loading Ordering SELECT Query Parameters Containers & Query Expressions Deployment Language Joins Packaging Persistence UPDATE & SELECT Clause Unit DELETE Bryan Basham – Overview of JPA v2.0 Slide 91
  • 92. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Ten Great Topics Not Covered 1) Composite keys; great for mapping to an existing DB schema 2) Primary key generation; eg) hashes or UUID 3) Native SQL queries 4) GROUP BY and HAVING clauses 5) More nuances of Entity relationships 6) More nuances to DB mappings 7) Entity lifecycle events and listeners (could be used for data manipulation or auditing) 8) Bean validation 9) Programmatic query APIs 10) Metamodel APIs Bryan Basham – Overview of JPA v2.0 Slide 92
  • 93. Rochester JUG: 11-Oct-2011 © Copyright 2011, Software Alchemy Resources ● JPA v2.0 – JSR 317 (click here) – Javadocs (click here) – Tutorials (click here) ● JPA Documentation – Wikipedia (click here) – Wikibooks (click here) Bryan Basham – Overview of JPA v2.0 Slide 93