SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Professional Open Source™




                            JPA




© JBoss, Inc. 2003, 2004.                          07/17/04   1
The @Id annotation
                                                              Professional Open Source™


  Using the javax.persistence.Id annotations is the simplest way of
   telling the persistence provider where the entity identity is stored.

  The @Id annotation marks afield or property as identity for an entity.




© JBoss, Inc. 2003, 2004.                                                                 2
The @IdClass annotation
                                                                                       Professional Open Source™


  The @IdClass annotation enables you to use more than one @Id annotation in a sensible way


  This is the basic problem with using more than one @Id field or property in an entity class: it is not
   obvious how to compare two instances in an automated fashion. This is especially true since in
   cases where composite keys are necessary




© JBoss, Inc. 2003, 2004.                                                                                          3
Using @IdClass
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               4
The @EmbeddedId annotation
                                                               Professional Open Source™


  Using the @EmbeddedId annotation is like moving the IdClass right
   into your entity and using the identity fields nested inside it to store
   entity data.

  See the example in next page




© JBoss, Inc. 2003, 2004.                                                                  5
The @EmbeddedId annotation
                                    Professional Open Source™




© JBoss, Inc. 2003, 2004.                                       6
Professional Open Source™




    GENERATING PRIMARY KEYS




© JBoss, Inc. 2003, 2004.                               7
Database sequences as generators
                                                          Professional Open Source™


  To use sequence generators, first define a sequence in the database.
   The following is a sample sequence for the USER_ID column in an
   Oracle database:

  CREATE SEQUENCE USER_SEQUENCE START WITH 1
   INCREMENT BY 10;

  @SequenceGenerator(name="USER_SEQUENCE_GENERATOR",
  sequenceName="USER_SEQUENCE",
  initialValue=1, allocationSize=10)

  The @SequenceGenerator annotation creates a sequence generator
   named USER_SEQUENCE_GENERATOR referencing the Oracle
   sequence we created and matching its setup.



© JBoss, Inc. 2003, 2004.                                                             8
Using Sequence Generator
                                  Professional Open Source™




© JBoss, Inc. 2003, 2004.                                     9
Sequence tables as generators
                                                               Professional Open Source™


  The first step is creating a table to use for generating values as
   follows :
  CREATE TABLE SEQUENCE_GENERATOR_TABLE
  (SEQUENCE_NAME VARCHAR2(80) NOT NULL,
  SEQUENCE_VALUE NUMBER(15) NOT NULL,
  PRIMARY KEY (SEQUENCE_NAME));

  The next step is to prepare the table for use by inserting the initial
   value manually as follows:

  INSERT INTO
  SEQUENCE_GENERATOR_TABLE (SEQUENCE_NAME,
   SEQUENCE_VALUE)
  VALUES ('USER_SEQUENCE', 1);


© JBoss, Inc. 2003, 2004.                                                                  10
Sequence tables as generators
                                                         Professional Open Source™


       Next step :
       @TableGenerator (name="USER_TABLE_GENERATOR",
       table="SEQUENCE_GENERATOR_TABLE",
       pkColumnName="SEQUENCE_NAME",
       valueColumnName="SEQUENCE_VALUE",
       pkColumnValue="USER_SEQUENCE")

  Next step :

       @Id
       @GeneratedValue(strategy=GenerationType.TABLE,
       generator="USER_TABLE_GENERATOR")
       @Column(name="USER_ID")
       protected Long userId;

© JBoss, Inc. 2003, 2004.                                                            11
Mapping embeddable classes
                                                          Professional Open Source™




                                    See next page for sample code



© JBoss, Inc. 2003, 2004.                                                             12
Mapping embeddable classes
                                    Professional Open Source™




© JBoss, Inc. 2003, 2004.                                       13
Unidirectional one-to-one relationship
                                                Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                   14
Bidirectional one-to-one
                                                              Professional Open Source™


  you can access EJBContext through DI. For example, a
   SessionContext could be injected into a bean as follows:




                            See next page for explanation
© JBoss, Inc. 2003, 2004.                                                                 15
Bidirectional one-to-one
                                                                      Professional Open Source™



  The @OneToOne annotation on the user field has two
   interesting things going on.
           – The first is the mappedBy="billingInfo" specification . This tells the
             container that the “owning” side of the relationship exists in the
             User class’s billingInfo instance variable.
           – The second interesting feature of the @OneToOne annotation on
             the user field is that the optional parameter is set to false this time.
             This means that a BillingInfo object cannot exist without a related
             User object.




© JBoss, Inc. 2003, 2004.                                                                         16
One-to-many bidirectional relationship
                                                Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                   17
Many-to-one as owning-side of relationship
                                                          Professional Open Source™


  For bidirectional one-to-many relationships,ManyToOne is always the
   owning side of the relationship.

  Because of this fact, the mappedBy element does not exist in the
   definition of the @ManyToOne annotation:




© JBoss, Inc. 2003, 2004.                                                             18
@ManyToMany
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               19
Mapping an entity
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               20
Professional Open Source™




© JBoss, Inc. 2003, 2004.                               21
Specifying the table
                              Professional Open Source™




© JBoss, Inc. 2003, 2004.                                 22
Mapping the columns
                                                                          Professional Open Source™




         If the insertable parameter is set to false, the field or property will not be
         included in the INSERT statement generated by the persistence provider
         to create a new record corresponding to the entity. Likewise, setting the
         updatable parameter to false excludes the field or property from being
         updated when the entity is saved. These two parameters are usually
         helpful in dealing with read-only data, like primary keys generated by the
         database.

© JBoss, Inc. 2003, 2004.                                                                             23
Mapping CLOBs and BLOBs
                                                            Professional Open Source™




 • Whether a field or property designated @Lob is a CLOB or a BLOB is
   determined by its type.
 • If the data is of type char[] or String, the persistence provider maps
   the data to a CLOB column. Otherwise, the column is mapped as a
   BLOB.
 • An extremely useful annotation to use in conjunction with @Lob is
   @Basic. @Basic can be marked on any attribute with direct-to-field
   mapping. Just as we have done for the picture field, the
   @Basic(fetch=FetchType.LAZY) specification causes the BLOB or
   CLOB data to be loaded from the database only when it is first
   accessed.
 • Postponing of loading of entity data from the database is known as
   lazy loading.



© JBoss, Inc. 2003, 2004.                                                               24
Mapping temporal types
                                                             Professional Open Source™


  The @Temporal annotation specifies which of these data types we
   want to map a java.util.Date or java.util.Calendar persistent data type
   to.
  Note this explicit mapping is redundant while using the java.sql.Date,
   java.sql.Time or java.sql.Timestamp Java types.
  If we do not specify a parameter for @Temporal annotation or omit it
   altogether, the persistence provider will assume the data type
   mapping to be TIMESTAMP




© JBoss, Inc. 2003, 2004.                                                                25
Mapping an entity to multiple tables
                                              Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                 26
Generating primary keys
                                 Professional Open Source™




© JBoss, Inc. 2003, 2004.                                    27
Mapping one-to-one relationships
                                                          Professional Open Source™


  Depending on where the foreign key resides, the relationship could
   be implemented in two different ways: using the @JoinColumn or the
   @PrimaryKeyJoinColumn annotation.

                                           User has a one-to-one
                                           unidirectional relationship
                                           with BillingInfo. The User
                                           and BillingInfo entities are
                                           mapped to the USERS and
                                           BILLING_INFO tables,
                                           respectively, and the USERS
                                           table has a foreign key
                                           reference to the
                                           BILLING_INFO table. Such
                                           associations are mapped
                                           using @JoinColumn.



© JBoss, Inc. 2003, 2004.                                                             28
Using @JoinColumn
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               29
Using @JoinColumn
                                                          Professional Open Source™


  Like the @Column annotation, the @JoinColumn annotation contains
   the updatable,insertable, table, and unique elements. The elements
   serve the same purposeas the elements of the @Column annotation.
   In our case, updatable is set to false, which means that the
   persistence provider would not update the foreign key even if the
   billingInfo reference were changed.

  If you have more than one column in the foreign key, you can use the
   JoinColumns annotation instead.




© JBoss, Inc. 2003, 2004.                                                             30
Using @PrimaryKeyJoinColumn
                                                         Professional Open Source™




                                     User has a one-to-one
                                     unidirectional relationship with
                                     BillingInfo. The User and
                                     BillingInfo entities are mapped to
                                     the USERS and BILLING_INFO
                                     tables, respectively, and the
                                     BILLING_INFO and USERS
                                     tables share the same primary
                                     key; the primary key of the
                                     BILLING_INFO table is also a
                                     foreign key referencing the
                                     primary key of the USERS table.
                                     Such associations are mapped
                                     using
                                     @PrimaryKeyJoinColumn.



© JBoss, Inc. 2003, 2004.                                                            31
Mapping a one-to-one relationship using @PrimaryKeyJoinColumn
                                                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                               32
One-to-many bidirectional relationship mapping
                                                        Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                           33
Many-to-one self-referencing relationship mapping
                                                           Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                              34
Many-to-many
                                                                         Professional Open Source™




                Many-to-many relationships are modeled in the database world
                using join tables. A join table essentially pairs foreign keys
                pointing to primary keys on either side of the relationship.




© JBoss, Inc. 2003, 2004.                                                                            35
Many-to-many relationship mapping
                                           Professional Open Source™




© JBoss, Inc. 2003, 2004.                                              36
Mapping inheritance
                                                  Professional Open Source™



  Entities in the hierarchy in below figure can be mapped to
   database tables using different types of inheritance
   mapping strategies supported by JPA:
           – Single table
           – Joined tables
           – Table per class




© JBoss, Inc. 2003, 2004.                                                     37
Single-table strategy
                                                               Professional Open Source™


  In the single-table strategy, all classes in the inheritance hierarchy are
   mapped to a single table. This means that the single table will contain
   a superset of all data stored in the class hierarchy. Different objects in
   the OO hierarchy are identified using a special column called a
   discriminator column. In effect, the discriminator column contains a
   value unique to the object type in a given row.




© JBoss, Inc. 2003, 2004.                                                                  38
Inheritance mapping using a single table
                                                  Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                     39
Joined-tables strategy
                                                            Professional Open Source™


  The joined-tables inheritance strategy uses one-to-one relationships
   to model OO inheritance. In effect, the joined-tables strategy involves
   creating separate tables for each entity in the OO hierarchy and
   relating direct descendants in the hierarchy with one-to-one
   relationships.
  The discriminator column in the USERS table is still used, primarily as
   a way of easily differentiating data types in the hierarchy.




© JBoss, Inc. 2003, 2004.                                                               40
Inheritance mapping using joined tables
                                                 Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                    41
Table-per-class strategy
                                                            Professional Open Source™


  Entity data are stored in their own tables even if they are inherited
   from the superclass. This is true even for the USER_ID primary key.




© JBoss, Inc. 2003, 2004.                                                               42
Inheritance mapping using the table-per-class strategy
                                                                Professional Open Source™




© JBoss, Inc. 2003, 2004.                                                                   43

Weitere ähnliche Inhalte

Was ist angesagt? (6)

2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
 
Xml session01
Xml session01Xml session01
Xml session01
 
JD Edwards & Peoplesoft 3 _ Victoria Cleven _ Enhance Usability using PeopleS...
JD Edwards & Peoplesoft 3 _ Victoria Cleven _ Enhance Usability using PeopleS...JD Edwards & Peoplesoft 3 _ Victoria Cleven _ Enhance Usability using PeopleS...
JD Edwards & Peoplesoft 3 _ Victoria Cleven _ Enhance Usability using PeopleS...
 
Comp elem skills
Comp elem skillsComp elem skills
Comp elem skills
 
What’s New For SQL Optimization In DB2 9 And DB2 10 For z/OS
What’s New For SQL Optimization In DB2 9 And DB2 10 For z/OSWhat’s New For SQL Optimization In DB2 9 And DB2 10 For z/OS
What’s New For SQL Optimization In DB2 9 And DB2 10 For z/OS
 
candi-binding-tutorial
candi-binding-tutorialcandi-binding-tutorial
candi-binding-tutorial
 

Andere mochten auch

Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
patinijava
 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
SFI
 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2
SFI
 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3
SFI
 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2
patinijava
 
FinelyMe-JustFit Intro
FinelyMe-JustFit IntroFinelyMe-JustFit Intro
FinelyMe-JustFit Intro
Cheng Ta Yeh
 
Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1
patinijava
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
patinijava
 

Andere mochten auch (20)

Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
Working with jpa
Working with jpaWorking with jpa
Working with jpa
 
JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2
 
Ejb5
Ejb5Ejb5
Ejb5
 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3
 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
 
Quickstart for continuous integration
Quickstart for continuous integrationQuickstart for continuous integration
Quickstart for continuous integration
 
FinelyMe-JustFit Intro
FinelyMe-JustFit IntroFinelyMe-JustFit Intro
FinelyMe-JustFit Intro
 
Continuous integration practices to improve the software quality
Continuous integration practices to improve the software qualityContinuous integration practices to improve the software quality
Continuous integration practices to improve the software quality
 
Introduction to developing modern web apps
Introduction to developing modern web appsIntroduction to developing modern web apps
Introduction to developing modern web apps
 
Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1
 
Designing Scalable Applications
Designing Scalable ApplicationsDesigning Scalable Applications
Designing Scalable Applications
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 
Continuous testing in agile projects 2015
Continuous testing in agile projects 2015Continuous testing in agile projects 2015
Continuous testing in agile projects 2015
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To Spring
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 

Ähnlich wie 15 jpa

01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modeling
thirumuru2012
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategies
thirumuru2012
 
10 conversations new
10 conversations new10 conversations new
10 conversations new
thirumuru2012
 
11 transitive persistence and filters
11 transitive persistence and filters11 transitive persistence and filters
11 transitive persistence and filters
thirumuru2012
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJB
odedns
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
thirumuru2012
 

Ähnlich wie 15 jpa (20)

14 hql
14 hql14 hql
14 hql
 
14 criteria api
14 criteria api14 criteria api
14 criteria api
 
01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modeling
 
13 caching latest
13 caching   latest13 caching   latest
13 caching latest
 
Learning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client DevelopersLearning To Run - XPages for Lotus Notes Client Developers
Learning To Run - XPages for Lotus Notes Client Developers
 
2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategies
 
10 conversations new
10 conversations new10 conversations new
10 conversations new
 
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBaseEmbeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
Embeddable Databases for Mobile Apps: Stress-Free Solutions with InterBase
 
Ef code first
Ef code firstEf code first
Ef code first
 
What's new in Exchange 2013?
What's new in Exchange 2013?What's new in Exchange 2013?
What's new in Exchange 2013?
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
11 transitive persistence and filters
11 transitive persistence and filters11 transitive persistence and filters
11 transitive persistence and filters
 
SAP integration sample payloads for Azure Logic Apps
SAP integration sample payloads for Azure Logic AppsSAP integration sample payloads for Azure Logic Apps
SAP integration sample payloads for Azure Logic Apps
 
JEE Course - EJB
JEE Course - EJBJEE Course - EJB
JEE Course - EJB
 
EJB 2
EJB 2EJB 2
EJB 2
 
Spring – Java-based Container Configuration
Spring – Java-based Container ConfigurationSpring – Java-based Container Configuration
Spring – Java-based Container Configuration
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
 
Introcution to EJB
Introcution to EJBIntrocution to EJB
Introcution to EJB
 

Mehr von thirumuru2012

Mehr von thirumuru2012 (6)

15 jpa introduction
15 jpa introduction15 jpa introduction
15 jpa introduction
 
12 hibernate int&cache
12  hibernate int&cache12  hibernate int&cache
12 hibernate int&cache
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1
 
09 transactions new
09 transactions new09 transactions new
09 transactions new
 
05 inheritance
05 inheritance05 inheritance
05 inheritance
 
04 dataaccess
04 dataaccess04 dataaccess
04 dataaccess
 

15 jpa

  • 1. Professional Open Source™ JPA © JBoss, Inc. 2003, 2004. 07/17/04 1
  • 2. The @Id annotation Professional Open Source™  Using the javax.persistence.Id annotations is the simplest way of telling the persistence provider where the entity identity is stored.  The @Id annotation marks afield or property as identity for an entity. © JBoss, Inc. 2003, 2004. 2
  • 3. The @IdClass annotation Professional Open Source™  The @IdClass annotation enables you to use more than one @Id annotation in a sensible way  This is the basic problem with using more than one @Id field or property in an entity class: it is not obvious how to compare two instances in an automated fashion. This is especially true since in cases where composite keys are necessary © JBoss, Inc. 2003, 2004. 3
  • 4. Using @IdClass Professional Open Source™ © JBoss, Inc. 2003, 2004. 4
  • 5. The @EmbeddedId annotation Professional Open Source™  Using the @EmbeddedId annotation is like moving the IdClass right into your entity and using the identity fields nested inside it to store entity data.  See the example in next page © JBoss, Inc. 2003, 2004. 5
  • 6. The @EmbeddedId annotation Professional Open Source™ © JBoss, Inc. 2003, 2004. 6
  • 7. Professional Open Source™ GENERATING PRIMARY KEYS © JBoss, Inc. 2003, 2004. 7
  • 8. Database sequences as generators Professional Open Source™  To use sequence generators, first define a sequence in the database. The following is a sample sequence for the USER_ID column in an Oracle database:  CREATE SEQUENCE USER_SEQUENCE START WITH 1 INCREMENT BY 10;  @SequenceGenerator(name="USER_SEQUENCE_GENERATOR",  sequenceName="USER_SEQUENCE",  initialValue=1, allocationSize=10)  The @SequenceGenerator annotation creates a sequence generator named USER_SEQUENCE_GENERATOR referencing the Oracle sequence we created and matching its setup. © JBoss, Inc. 2003, 2004. 8
  • 9. Using Sequence Generator Professional Open Source™ © JBoss, Inc. 2003, 2004. 9
  • 10. Sequence tables as generators Professional Open Source™  The first step is creating a table to use for generating values as follows :  CREATE TABLE SEQUENCE_GENERATOR_TABLE  (SEQUENCE_NAME VARCHAR2(80) NOT NULL,  SEQUENCE_VALUE NUMBER(15) NOT NULL,  PRIMARY KEY (SEQUENCE_NAME));  The next step is to prepare the table for use by inserting the initial value manually as follows:  INSERT INTO  SEQUENCE_GENERATOR_TABLE (SEQUENCE_NAME, SEQUENCE_VALUE)  VALUES ('USER_SEQUENCE', 1); © JBoss, Inc. 2003, 2004. 10
  • 11. Sequence tables as generators Professional Open Source™  Next step :  @TableGenerator (name="USER_TABLE_GENERATOR",  table="SEQUENCE_GENERATOR_TABLE",  pkColumnName="SEQUENCE_NAME",  valueColumnName="SEQUENCE_VALUE",  pkColumnValue="USER_SEQUENCE")  Next step :  @Id  @GeneratedValue(strategy=GenerationType.TABLE,  generator="USER_TABLE_GENERATOR")  @Column(name="USER_ID")  protected Long userId; © JBoss, Inc. 2003, 2004. 11
  • 12. Mapping embeddable classes Professional Open Source™ See next page for sample code © JBoss, Inc. 2003, 2004. 12
  • 13. Mapping embeddable classes Professional Open Source™ © JBoss, Inc. 2003, 2004. 13
  • 14. Unidirectional one-to-one relationship Professional Open Source™ © JBoss, Inc. 2003, 2004. 14
  • 15. Bidirectional one-to-one Professional Open Source™  you can access EJBContext through DI. For example, a SessionContext could be injected into a bean as follows: See next page for explanation © JBoss, Inc. 2003, 2004. 15
  • 16. Bidirectional one-to-one Professional Open Source™  The @OneToOne annotation on the user field has two interesting things going on. – The first is the mappedBy="billingInfo" specification . This tells the container that the “owning” side of the relationship exists in the User class’s billingInfo instance variable. – The second interesting feature of the @OneToOne annotation on the user field is that the optional parameter is set to false this time. This means that a BillingInfo object cannot exist without a related User object. © JBoss, Inc. 2003, 2004. 16
  • 17. One-to-many bidirectional relationship Professional Open Source™ © JBoss, Inc. 2003, 2004. 17
  • 18. Many-to-one as owning-side of relationship Professional Open Source™  For bidirectional one-to-many relationships,ManyToOne is always the owning side of the relationship.  Because of this fact, the mappedBy element does not exist in the definition of the @ManyToOne annotation: © JBoss, Inc. 2003, 2004. 18
  • 19. @ManyToMany Professional Open Source™ © JBoss, Inc. 2003, 2004. 19
  • 20. Mapping an entity Professional Open Source™ © JBoss, Inc. 2003, 2004. 20
  • 21. Professional Open Source™ © JBoss, Inc. 2003, 2004. 21
  • 22. Specifying the table Professional Open Source™ © JBoss, Inc. 2003, 2004. 22
  • 23. Mapping the columns Professional Open Source™ If the insertable parameter is set to false, the field or property will not be included in the INSERT statement generated by the persistence provider to create a new record corresponding to the entity. Likewise, setting the updatable parameter to false excludes the field or property from being updated when the entity is saved. These two parameters are usually helpful in dealing with read-only data, like primary keys generated by the database. © JBoss, Inc. 2003, 2004. 23
  • 24. Mapping CLOBs and BLOBs Professional Open Source™ • Whether a field or property designated @Lob is a CLOB or a BLOB is determined by its type. • If the data is of type char[] or String, the persistence provider maps the data to a CLOB column. Otherwise, the column is mapped as a BLOB. • An extremely useful annotation to use in conjunction with @Lob is @Basic. @Basic can be marked on any attribute with direct-to-field mapping. Just as we have done for the picture field, the @Basic(fetch=FetchType.LAZY) specification causes the BLOB or CLOB data to be loaded from the database only when it is first accessed. • Postponing of loading of entity data from the database is known as lazy loading. © JBoss, Inc. 2003, 2004. 24
  • 25. Mapping temporal types Professional Open Source™  The @Temporal annotation specifies which of these data types we want to map a java.util.Date or java.util.Calendar persistent data type to.  Note this explicit mapping is redundant while using the java.sql.Date, java.sql.Time or java.sql.Timestamp Java types.  If we do not specify a parameter for @Temporal annotation or omit it altogether, the persistence provider will assume the data type mapping to be TIMESTAMP © JBoss, Inc. 2003, 2004. 25
  • 26. Mapping an entity to multiple tables Professional Open Source™ © JBoss, Inc. 2003, 2004. 26
  • 27. Generating primary keys Professional Open Source™ © JBoss, Inc. 2003, 2004. 27
  • 28. Mapping one-to-one relationships Professional Open Source™  Depending on where the foreign key resides, the relationship could be implemented in two different ways: using the @JoinColumn or the @PrimaryKeyJoinColumn annotation. User has a one-to-one unidirectional relationship with BillingInfo. The User and BillingInfo entities are mapped to the USERS and BILLING_INFO tables, respectively, and the USERS table has a foreign key reference to the BILLING_INFO table. Such associations are mapped using @JoinColumn. © JBoss, Inc. 2003, 2004. 28
  • 29. Using @JoinColumn Professional Open Source™ © JBoss, Inc. 2003, 2004. 29
  • 30. Using @JoinColumn Professional Open Source™  Like the @Column annotation, the @JoinColumn annotation contains the updatable,insertable, table, and unique elements. The elements serve the same purposeas the elements of the @Column annotation. In our case, updatable is set to false, which means that the persistence provider would not update the foreign key even if the billingInfo reference were changed.  If you have more than one column in the foreign key, you can use the JoinColumns annotation instead. © JBoss, Inc. 2003, 2004. 30
  • 31. Using @PrimaryKeyJoinColumn Professional Open Source™ User has a one-to-one unidirectional relationship with BillingInfo. The User and BillingInfo entities are mapped to the USERS and BILLING_INFO tables, respectively, and the BILLING_INFO and USERS tables share the same primary key; the primary key of the BILLING_INFO table is also a foreign key referencing the primary key of the USERS table. Such associations are mapped using @PrimaryKeyJoinColumn. © JBoss, Inc. 2003, 2004. 31
  • 32. Mapping a one-to-one relationship using @PrimaryKeyJoinColumn Professional Open Source™ © JBoss, Inc. 2003, 2004. 32
  • 33. One-to-many bidirectional relationship mapping Professional Open Source™ © JBoss, Inc. 2003, 2004. 33
  • 34. Many-to-one self-referencing relationship mapping Professional Open Source™ © JBoss, Inc. 2003, 2004. 34
  • 35. Many-to-many Professional Open Source™ Many-to-many relationships are modeled in the database world using join tables. A join table essentially pairs foreign keys pointing to primary keys on either side of the relationship. © JBoss, Inc. 2003, 2004. 35
  • 36. Many-to-many relationship mapping Professional Open Source™ © JBoss, Inc. 2003, 2004. 36
  • 37. Mapping inheritance Professional Open Source™  Entities in the hierarchy in below figure can be mapped to database tables using different types of inheritance mapping strategies supported by JPA: – Single table – Joined tables – Table per class © JBoss, Inc. 2003, 2004. 37
  • 38. Single-table strategy Professional Open Source™  In the single-table strategy, all classes in the inheritance hierarchy are mapped to a single table. This means that the single table will contain a superset of all data stored in the class hierarchy. Different objects in the OO hierarchy are identified using a special column called a discriminator column. In effect, the discriminator column contains a value unique to the object type in a given row. © JBoss, Inc. 2003, 2004. 38
  • 39. Inheritance mapping using a single table Professional Open Source™ © JBoss, Inc. 2003, 2004. 39
  • 40. Joined-tables strategy Professional Open Source™  The joined-tables inheritance strategy uses one-to-one relationships to model OO inheritance. In effect, the joined-tables strategy involves creating separate tables for each entity in the OO hierarchy and relating direct descendants in the hierarchy with one-to-one relationships.  The discriminator column in the USERS table is still used, primarily as a way of easily differentiating data types in the hierarchy. © JBoss, Inc. 2003, 2004. 40
  • 41. Inheritance mapping using joined tables Professional Open Source™ © JBoss, Inc. 2003, 2004. 41
  • 42. Table-per-class strategy Professional Open Source™  Entity data are stored in their own tables even if they are inherited from the superclass. This is true even for the USER_ID primary key. © JBoss, Inc. 2003, 2004. 42
  • 43. Inheritance mapping using the table-per-class strategy Professional Open Source™ © JBoss, Inc. 2003, 2004. 43