SlideShare una empresa de Scribd logo
1 de 43
Professional Open Source™




           Association Mappings




© JBoss, Inc. 2003, 2004.                          07/17/04   1
Fine Grained Domain models                        Professional Open Source™




         A major objective of Hibernate is support for fine-grained domain models, which is the
         most important requirement for a rich domain model. It’s one reason why we work with
         POJOs. In crude terms, fine-grained means more classes than tables.

         For example, a user may have both a billing address and a home address. In the
         database, you may have a single USERS table with the columns
         BILLING_STREET,BILLING_CITY, and BILLING_ZIPCODE, along with HOME_STREET,
         HOME_CITY, and HOME_ZIPCODE. But there will be two classes User and Address

         This fine grained domain model improves code reuse




© JBoss, Inc. 2003, 2004.                                                                      07/17/04   2
Collections of Value types
                                                                              Professional Open Source™


  An object of value type has no database identity; it belongs to an entity instance,
  and its persistent state is embedded in the table row of the owning entity—at least,
  if an entity has a reference to a single instance of a value type.


  If an entity class has a collection of value types (or a collection of references to value-
   typed instances), you need an additional table, the so-called collection table.


  Before you map collections of value types to collection tables, remember that value-
   typed classes don’t have identifiers or identifier properties.

  The lifespan of a value-type instance is bounded by the lifespan of the owning
   entity instance. A value type doesn’t support shared references.




© JBoss, Inc. 2003, 2004.                                                                                 3
ValueType Vs Entity
                                                         Professional Open Source™


  When shared references to an object is needed, then model that
   class as an Entity else make the class as a ValueType




© JBoss, Inc. 2003, 2004.                                                            4
Understanding Java identity and equality
                                                             Professional Open Source™


  There are three methods for identifying objects:

 3. Objects are identical if they occupy the same memory location in the
    JVM. This can be checked by using the == operator. This concept is
    known as object identity.
 4. Objects are equal if they have the same value, as defined by the
  equals(Object o) method. Classes that don’t explicitly override this
  method inherit the implementation defined by java.lang.Object, which
  compares object identity. This concept is known as equality.
 3 Objects stored in a relational database are identical if they represent
    the same row or, equivalently, if they share the same table and
    primary key value. This concept is known as database identity.




© JBoss, Inc. 2003, 2004.                                                                5
Handling database identity
                                                               Professional Open Source™


  Hibernate exposes database identity to the application in two ways:
  ■ The value of the identifier property of a persistent instance
  ■ The value returned by Session.getIdentifier(Object entity)

  In addition to operations for testing Java object identity, (a == b), and
   object equality, ( a.equals(b) ), you may now use
   a.getId().equals( b.getId() ) to test database identity.




© JBoss, Inc. 2003, 2004.                                                                  6
Selecting a primary key
                                                                              Professional Open Source™

  The candidate key is a column or set of columns that could be used to
   identify a particular row in a table.

  To become a primary key, a candidate key must satisfy the following
   properties:
           – Its value (for any column of the candidate key) is never null.
           – Each row has a unique value.
           – The value of a particular row never changes.



  If a table has only one identifying attribute, it’s, by definition, the
   primary key.

  However, several columns or combinations of columns may satisfy
   these properties for a particular table; you choose between candidate
   keys to decide the best primary key for the table.


© JBoss, Inc. 2003, 2004.                                                                                 7
Natural Key
                                                              Professional Open Source™


  A natural key is a key with business meaning: an attribute or
   combination of attributes that is unique by virtue of its business
   semantics.

  Examples  the U.S. Social Security Number and Australian Tax File
   Number.



  Distinguishing natural keys is simple : If a candidate key attribute has
   meaning outside the database context, it’s a natural key, whether or
   not it’s automatically generated.




© JBoss, Inc. 2003, 2004.                                                                 8
Surrogate Key
                                                           Professional Open Source™


  Surrogate keys have no business meaning—they’re unique values
   generated by the database or application. Application users ideally
  don’t see or refer to these key values; they’re part of the system
   internals.




© JBoss, Inc. 2003, 2004.                                                              9
Selecting a key Generator
                                                              Professional Open Source™


  Hibernate has several built-in identifier-generation strategies.




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




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




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




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




© JBoss, Inc. 2003, 2004.                               14
Configuring a generator
                                                                            Professional Open Source™


  Some of the built-in identifier generators can be configured with
   options. In a native Hibernate XML mapping, you define options as
   pairs of keys and values:

  <id name="id" type="long" column="person_id">
        <generator class="sequence">
                           <param name="sequence">person_id_sequence</param>
                   </generator>
  </id>




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




             CLASS MAPPING OPTIONS




© JBoss, Inc. 2003, 2004.                                   16
Dynamic SQL generation
                                                             Professional Open Source™


  By default, Hibernate creates SQL statements for each persistent
   class on startup. These statements are simple create, read, update,
   and delete operations for reading a single row, deleting a row, and so
   on.
  The generated SQL statement updates all columns, and if the value
   of a particular column isn’t modified, the statement sets it to its old
   value.
  In some situations, such as a legacy table with hundreds of columns
   where the SQL statements will be large for even the simplest
   operations (say, only one column needs updating), you have to turn
   off this startup SQL generation and switch to dynamic statements
   generated at runtime.
  Two attributes for disabling CRUD SQL generation on startup are
   available on the <class> mapping element:




© JBoss, Inc. 2003, 2004.                                                                17
Making an entity immutable
                                                                Professional Open Source™


  Instances of a particular class may be immutable.
  A Bid made for an item is immutable. Hence, no UPDATE statement
   ever needs to be executed on the BID table.

  Hibernate can also make a few other optimizations, such as avoiding
   dirty checking, if you map an immutable class with the mutable
  attribute set to false:




         A POJO is immutable if no public setter methods for any properties
         of the class are exposed—all values are set in the constructor.
         Instead of private setter methods, you often prefer direct field
         access by Hibernate for immutable persistent classes, so you don’t
         have to write useless accessor methods.

© JBoss, Inc. 2003, 2004.                                                                   18
Naming entities for querying
                                                            Professional Open Source™


  By default, all class names are automatically “imported” into the
   namespace of the Hibernate query language, HQL. In other words,
   you can use the short class names without a package prefix in HQL,
   which is convenient. However, this auto import can be turned off if two
   classes with the same name exist for a given SessionFactory, maybe
   in different packages of the domain model.
  You can turn off auto-import of names into the HQL namespace for
   particular mapping files with the autoimport=“false" setting on the
   <hibernate-mapping> root element.
  Entity names can also be imported explicitly into the HQL
   namespace. You can even import classes and interfaces that aren’t
   explicitly mapped, so a short name can be used in polymorphic HQL
   queries:




© JBoss, Inc. 2003, 2004.                                                               19
Naming entities for querying
                                                             Professional Open Source™


  You can now use an HQL query such as from IAuditable to retrieve all
   persistent instances of classes that implement the
   auction.model.Auditable interface.

  Note that the <import> element , like all other immediate child
   elements of <hibernate-mapping>, is an application-wide declaration,
   so you don’t have to (and can’t) duplicate this in other mapping files.




© JBoss, Inc. 2003, 2004.                                                                20
Declaring a package name
                                  Professional Open Source™




© JBoss, Inc. 2003, 2004.                                     21
Mapping components
                                  Professional Open Source™


  See the composition example.




© JBoss, Inc. 2003, 2004.                                     22
Selecting a collection interface
                                                               Professional Open Source™


 A java.util.Set is mapped with a <set> element. Initialize the collection
     with a java.util.HashSet. The order of its elements isn’t preserved,
     and duplicate elements aren’t allowed. This is the most common
     persistent collection in a typical Hibernate application.

 A java.util.SortedSet can be mapped with <set>, and the sort attribute
     can be set to either a comparator or natural ordering for in-memory
     sorting. Initialize the collection with a java.util.TreeSet instance.

 A java.util.List can be mapped with <list>, preserving the position of
 each element with an additional index column in the collection table.
     Initialize with a java.util.ArrayList.




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


  A java.util.Collection can be mapped with <bag> or <idbag>. Java
  doesn’t have a Bag interface or an implementation; however,
   java.util.Collection allows bag semantics (possible duplicates,
   no element order is preserved). Hibernate supports persistent bags
   (it uses lists internally but ignores the index of the elements). Use a
   java.util.ArrayList to initialize a bag collection.

  A java.util.Map can be mapped with <map>, preserving key and value
  pairs. Use a java.util.HashMap to initialize a property.

  A java.util.SortedMap can be mapped with <map> element, and the
   sort attribute can be set to either a comparator or natural ordering for
   in-memory sorting. Initialize the collection with a java.util.TreeMap
   instance.



© JBoss, Inc. 2003, 2004.                                                                 24
Mapping a set
                                                            Professional Open Source™


  The simplest implementation is a Set of String image filenames. First,
   add a collection property to the Item class:




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


  The image filenames are stored in a table named ITEM_IMAGE, the
   collection table. From the point of view of the database, this table is a
   separate entity, a separate table, but Hibernate hides this for you.

  The <key> element declares the foreign key column in the collection
   table that references the primary key ITEM_ID of the owning entity.
   The <element> tag declares this collection as a collection of value
   type instances—in this case, of strings.

  A set can’t contain duplicate elements, so the primary key of the
   ITEM_IMAGE collection table is a composite of both columns in
   the <set> declaration: ITEM_ID and FILENAME.




© JBoss, Inc. 2003, 2004.                                                                 26
Disadvantages of <set>
                                                      Professional Open Source™


  A set is very inefficient if/when adding to a large collection,
   because Hibernate has to load the entire collection into memory
   in order to ensure that uniqueness is preserved.




© JBoss, Inc. 2003, 2004.                                                         27
Mapping an identifier bag
                                                              Professional Open Source™


  An unordered collection that permits duplicate elements is
   called a bag.
  Curiously, the Java Collections framework doesn’t include a bag
   implementation.However, the java.util.Collection interface has bag
   semantics, so you only need a matching implementation.

  Write the collection property with the java.util.Collection interface,
  and, on declaration, initialize it with an ArrayList of the JDK. Map the
  collection in Hibernate with a standard <bag> or <idbag> element.

  Hibernate has a built-in PersistentBag that can deal with lists;
   however, consistent with the contract of a bag, it ignores the
   position of elements in the ArrayList. In other words, you get a
   persistent Collection.



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




         You also have to modify the collection table to permit duplicate FILENAMEs;
         the table needs a different primary key. An <idbag> mapping adds a surrogate
         key column to the collection table, much like the synthetic identifiers you use for
         entity classes.
         Note that the native generator for primary keys isn’t supported for <idbag>
         mappings
© JBoss, Inc. 2003, 2004.                                                                                  29
Mapping a list
                                                            Professional Open Source™


  If you wish to preserve the order in which images are attached to the
   Item, u can use list




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


  A <list> mapping requires the addition of an index column to the
   collection table.
  The index column defines the position of the element in the collection.
   Thus,Hibernate is able to preserve the ordering of the collection
   elements.

  The primary key of the collection table is a composite of ITEM_ID and
   POSITION.
  Notice that duplicate elements (FILENAME) are now allowed,




© JBoss, Inc. 2003, 2004.                                                               31
Mapping a map
                                                                     Professional Open Source™




         The primary key of the collection table is a composite of ITEM_ID and
         IMAGENAME. The IMAGENAME column holds the keys of the map. Again,
         duplicate elements are allowed;



© JBoss, Inc. 2003, 2004.                                                                        32
Sorted and ordered collections
                                                               Professional Open Source™


        A sorted collection is sorted in memory using a Java comparator.
        An ordered collection is ordered at the database level using an SQL
        query with an order by clause.




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


  By specifying sort="natural", you tell Hibernate to use a SortedMap
   and to sort the image names according to the compareTo() method of
   java.lang.String. If you need some other sort algorithm (for example,
   reverse alphabetical order),you may specify the name of a class that
   implements java.util.Comparator in the sort attribute. For example:




© JBoss, Inc. 2003, 2004.                                                              34
Sorting Sets
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               35
Ordering Collections
                                                          Professional Open Source™


  Instead of switching to the Sorted* interfaces and the (Tree*
  implementations), you may want to work with a linked map and to sort
   elements on the database side, not in memory.




© JBoss, Inc. 2003, 2004.                                                             36
Ordering Map
                                                           Professional Open Source™


  The expression in the order-by attribute is a fragment of an SQL order
   by clause. In this case, Hibernate orders the collection elements by
   the IMAGENAME column in ascending order during loading of the
   collection. You can even include an SQL function call in the order-by
   attribute:




© JBoss, Inc. 2003, 2004.                                                              37
Ordering Set
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               38
Ordering idbag
                            Professional Open Source™




© JBoss, Inc. 2003, 2004.                               39
Collections of components
                                                                                 Professional Open Source™




              As you can see from the composition association style (the black diamond),
              Image is a component of Item, and Item is the entity that is responsible for
              the lifecycle of Image instances.

              The multiplicity of the association further declares this association as many-
              valued—that is, many (or zero) Image instances for the same Item instance.




© JBoss, Inc. 2003, 2004.                                                                                    40
Mapping Collection of Components
                                                          Professional Open Source™


  Collections of components are mapped similarly to collections of JDK
   value type. The only difference is the use of <composite-element>
   instead of an <element> tag. An ordered set of images (internally, a
   LinkedHashSet) can be mapped like this:




         See next page for example data


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


  The tables with example data are shown in figure




              This is a set, so the primary key of the collection table is a composite of the
              key column and all element columns: ITEM_ID, IMAGENAME,
              FILENAME, SIZEX, andSIZEY.

               Because these columns all appear in the primary key, you needed to
              declare them with not-null="true" (or make sure they’re NOT NULL in any
              existing schema). No column in a composite primary key can be nullable—
              you can’t identify what you don’t know. This is probably a disadvantage of
              this particular mapping.



© JBoss, Inc. 2003, 2004.                                                                                      42
Avoiding not-null columns
                                                            Professional Open Source™

  Analogous to the additional surrogate identifier property an <idbag>
   offers, a surrogate key column would come in handy now.




© JBoss, Inc. 2003, 2004.                                                               43

Más contenido relacionado

La actualidad más candente

Hibernate
HibernateHibernate
HibernateAjay K
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsTonny Madsen
 
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)Philip Langer
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句renguzi
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Rohit Kelapure
 
Research/Inquiry Project Learning Contract Menu Spring 2012, Lester and Hamilton
Research/Inquiry Project Learning Contract Menu Spring 2012, Lester and HamiltonResearch/Inquiry Project Learning Contract Menu Spring 2012, Lester and Hamilton
Research/Inquiry Project Learning Contract Menu Spring 2012, Lester and HamiltonBuffy Hamilton
 

La actualidad más candente (19)

S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
JDT Fundamentals 2010
JDT Fundamentals 2010JDT Fundamentals 2010
JDT Fundamentals 2010
 
Hibernate
HibernateHibernate
Hibernate
 
Form part1
Form part1Form part1
Form part1
 
Les02
Les02Les02
Les02
 
Java beans
Java beansJava beans
Java beans
 
15 jpa introduction
15 jpa introduction15 jpa introduction
15 jpa introduction
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
 
introduction of Java beans
introduction of Java beansintroduction of Java beans
introduction of Java beans
 
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
From UML Profiles to EMF Profiles and Beyond (TOOLS'11)
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Jpa
JpaJpa
Jpa
 
L0033 - JFace
L0033 - JFaceL0033 - JFace
L0033 - JFace
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Javabean1
Javabean1Javabean1
Javabean1
 
Research/Inquiry Project Learning Contract Menu Spring 2012, Lester and Hamilton
Research/Inquiry Project Learning Contract Menu Spring 2012, Lester and HamiltonResearch/Inquiry Project Learning Contract Menu Spring 2012, Lester and Hamilton
Research/Inquiry Project Learning Contract Menu Spring 2012, Lester and Hamilton
 

Similar a 06 association of value types

01 persistence and domain modeling
01 persistence and domain modeling01 persistence and domain modeling
01 persistence and domain modelingthirumuru2012
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategiesthirumuru2012
 
11 transitive persistence and filters
11 transitive persistence and filters11 transitive persistence and filters
11 transitive persistence and filtersthirumuru2012
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.Luigi Viggiano
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformBozhidar Bozhanov
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaArun Gupta
 
Using the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresUsing the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresArun Gupta
 
Understanding
Understanding Understanding
Understanding Arun Gupta
 
Java development with the dynamo framework
Java development with the dynamo frameworkJava development with the dynamo framework
Java development with the dynamo frameworkPatrick Deenen
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-onhomeworkping7
 
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 DevelopersKathy Brown
 
10 conversations new
10 conversations new10 conversations new
10 conversations newthirumuru2012
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 

Similar a 06 association of value types (20)

14 hql
14 hql14 hql
14 hql
 
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
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategies
 
14 criteria api
14 criteria api14 criteria api
14 criteria api
 
11 transitive persistence and filters
11 transitive persistence and filters11 transitive persistence and filters
11 transitive persistence and filters
 
05 inheritance
05 inheritance05 inheritance
05 inheritance
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platform
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
 
Oops
OopsOops
Oops
 
Using the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 featuresUsing the latest Java Persistence API 2.0 features
Using the latest Java Persistence API 2.0 features
 
Understanding
Understanding Understanding
Understanding
 
Ef code first
Ef code firstEf code first
Ef code first
 
Java development with the dynamo framework
Java development with the dynamo frameworkJava development with the dynamo framework
Java development with the dynamo framework
 
159747608 a-training-report-on
159747608 a-training-report-on159747608 a-training-report-on
159747608 a-training-report-on
 
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
 
En webinar jpa v2final
En webinar jpa v2finalEn webinar jpa v2final
En webinar jpa v2final
 
10 conversations new
10 conversations new10 conversations new
10 conversations new
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 

Más de thirumuru2012

12 hibernate int&cache
12  hibernate int&cache12  hibernate int&cache
12 hibernate int&cachethirumuru2012
 
09 transactions new1
09 transactions new109 transactions new1
09 transactions new1thirumuru2012
 
07 association of entities
07 association of entities07 association of entities
07 association of entitiesthirumuru2012
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroductionthirumuru2012
 

Más de thirumuru2012 (6)

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
 
07 association of entities
07 association of entities07 association of entities
07 association of entities
 
04 dataaccess
04 dataaccess04 dataaccess
04 dataaccess
 
02 hibernateintroduction
02 hibernateintroduction02 hibernateintroduction
02 hibernateintroduction
 

Último

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

06 association of value types

  • 1. Professional Open Source™ Association Mappings © JBoss, Inc. 2003, 2004. 07/17/04 1
  • 2. Fine Grained Domain models Professional Open Source™ A major objective of Hibernate is support for fine-grained domain models, which is the most important requirement for a rich domain model. It’s one reason why we work with POJOs. In crude terms, fine-grained means more classes than tables. For example, a user may have both a billing address and a home address. In the database, you may have a single USERS table with the columns BILLING_STREET,BILLING_CITY, and BILLING_ZIPCODE, along with HOME_STREET, HOME_CITY, and HOME_ZIPCODE. But there will be two classes User and Address This fine grained domain model improves code reuse © JBoss, Inc. 2003, 2004. 07/17/04 2
  • 3. Collections of Value types Professional Open Source™  An object of value type has no database identity; it belongs to an entity instance,  and its persistent state is embedded in the table row of the owning entity—at least,  if an entity has a reference to a single instance of a value type.  If an entity class has a collection of value types (or a collection of references to value- typed instances), you need an additional table, the so-called collection table.  Before you map collections of value types to collection tables, remember that value- typed classes don’t have identifiers or identifier properties.  The lifespan of a value-type instance is bounded by the lifespan of the owning entity instance. A value type doesn’t support shared references. © JBoss, Inc. 2003, 2004. 3
  • 4. ValueType Vs Entity Professional Open Source™  When shared references to an object is needed, then model that class as an Entity else make the class as a ValueType © JBoss, Inc. 2003, 2004. 4
  • 5. Understanding Java identity and equality Professional Open Source™  There are three methods for identifying objects: 3. Objects are identical if they occupy the same memory location in the JVM. This can be checked by using the == operator. This concept is known as object identity. 4. Objects are equal if they have the same value, as defined by the  equals(Object o) method. Classes that don’t explicitly override this  method inherit the implementation defined by java.lang.Object, which  compares object identity. This concept is known as equality. 3 Objects stored in a relational database are identical if they represent the same row or, equivalently, if they share the same table and primary key value. This concept is known as database identity. © JBoss, Inc. 2003, 2004. 5
  • 6. Handling database identity Professional Open Source™  Hibernate exposes database identity to the application in two ways:  ■ The value of the identifier property of a persistent instance  ■ The value returned by Session.getIdentifier(Object entity)  In addition to operations for testing Java object identity, (a == b), and object equality, ( a.equals(b) ), you may now use a.getId().equals( b.getId() ) to test database identity. © JBoss, Inc. 2003, 2004. 6
  • 7. Selecting a primary key Professional Open Source™  The candidate key is a column or set of columns that could be used to identify a particular row in a table.  To become a primary key, a candidate key must satisfy the following properties: – Its value (for any column of the candidate key) is never null. – Each row has a unique value. – The value of a particular row never changes.  If a table has only one identifying attribute, it’s, by definition, the primary key.  However, several columns or combinations of columns may satisfy these properties for a particular table; you choose between candidate keys to decide the best primary key for the table. © JBoss, Inc. 2003, 2004. 7
  • 8. Natural Key Professional Open Source™  A natural key is a key with business meaning: an attribute or combination of attributes that is unique by virtue of its business semantics.  Examples  the U.S. Social Security Number and Australian Tax File Number.  Distinguishing natural keys is simple : If a candidate key attribute has meaning outside the database context, it’s a natural key, whether or not it’s automatically generated. © JBoss, Inc. 2003, 2004. 8
  • 9. Surrogate Key Professional Open Source™  Surrogate keys have no business meaning—they’re unique values generated by the database or application. Application users ideally  don’t see or refer to these key values; they’re part of the system internals. © JBoss, Inc. 2003, 2004. 9
  • 10. Selecting a key Generator Professional Open Source™  Hibernate has several built-in identifier-generation strategies. © JBoss, Inc. 2003, 2004. 10
  • 11. Professional Open Source™ © JBoss, Inc. 2003, 2004. 11
  • 12. Professional Open Source™ © JBoss, Inc. 2003, 2004. 12
  • 13. Professional Open Source™ © JBoss, Inc. 2003, 2004. 13
  • 14. Professional Open Source™ © JBoss, Inc. 2003, 2004. 14
  • 15. Configuring a generator Professional Open Source™  Some of the built-in identifier generators can be configured with options. In a native Hibernate XML mapping, you define options as pairs of keys and values:  <id name="id" type="long" column="person_id">  <generator class="sequence">  <param name="sequence">person_id_sequence</param>  </generator>  </id> © JBoss, Inc. 2003, 2004. 15
  • 16. Professional Open Source™ CLASS MAPPING OPTIONS © JBoss, Inc. 2003, 2004. 16
  • 17. Dynamic SQL generation Professional Open Source™  By default, Hibernate creates SQL statements for each persistent class on startup. These statements are simple create, read, update, and delete operations for reading a single row, deleting a row, and so on.  The generated SQL statement updates all columns, and if the value of a particular column isn’t modified, the statement sets it to its old value.  In some situations, such as a legacy table with hundreds of columns where the SQL statements will be large for even the simplest operations (say, only one column needs updating), you have to turn off this startup SQL generation and switch to dynamic statements generated at runtime.  Two attributes for disabling CRUD SQL generation on startup are available on the <class> mapping element: © JBoss, Inc. 2003, 2004. 17
  • 18. Making an entity immutable Professional Open Source™  Instances of a particular class may be immutable.  A Bid made for an item is immutable. Hence, no UPDATE statement ever needs to be executed on the BID table.  Hibernate can also make a few other optimizations, such as avoiding dirty checking, if you map an immutable class with the mutable  attribute set to false: A POJO is immutable if no public setter methods for any properties of the class are exposed—all values are set in the constructor. Instead of private setter methods, you often prefer direct field access by Hibernate for immutable persistent classes, so you don’t have to write useless accessor methods. © JBoss, Inc. 2003, 2004. 18
  • 19. Naming entities for querying Professional Open Source™  By default, all class names are automatically “imported” into the namespace of the Hibernate query language, HQL. In other words, you can use the short class names without a package prefix in HQL, which is convenient. However, this auto import can be turned off if two classes with the same name exist for a given SessionFactory, maybe in different packages of the domain model.  You can turn off auto-import of names into the HQL namespace for particular mapping files with the autoimport=“false" setting on the <hibernate-mapping> root element.  Entity names can also be imported explicitly into the HQL namespace. You can even import classes and interfaces that aren’t explicitly mapped, so a short name can be used in polymorphic HQL queries: © JBoss, Inc. 2003, 2004. 19
  • 20. Naming entities for querying Professional Open Source™  You can now use an HQL query such as from IAuditable to retrieve all persistent instances of classes that implement the auction.model.Auditable interface.  Note that the <import> element , like all other immediate child elements of <hibernate-mapping>, is an application-wide declaration, so you don’t have to (and can’t) duplicate this in other mapping files. © JBoss, Inc. 2003, 2004. 20
  • 21. Declaring a package name Professional Open Source™ © JBoss, Inc. 2003, 2004. 21
  • 22. Mapping components Professional Open Source™  See the composition example. © JBoss, Inc. 2003, 2004. 22
  • 23. Selecting a collection interface Professional Open Source™ A java.util.Set is mapped with a <set> element. Initialize the collection with a java.util.HashSet. The order of its elements isn’t preserved, and duplicate elements aren’t allowed. This is the most common persistent collection in a typical Hibernate application. A java.util.SortedSet can be mapped with <set>, and the sort attribute can be set to either a comparator or natural ordering for in-memory sorting. Initialize the collection with a java.util.TreeSet instance. A java.util.List can be mapped with <list>, preserving the position of each element with an additional index column in the collection table. Initialize with a java.util.ArrayList. © JBoss, Inc. 2003, 2004. 23
  • 24. Professional Open Source™  A java.util.Collection can be mapped with <bag> or <idbag>. Java  doesn’t have a Bag interface or an implementation; however, java.util.Collection allows bag semantics (possible duplicates, no element order is preserved). Hibernate supports persistent bags (it uses lists internally but ignores the index of the elements). Use a java.util.ArrayList to initialize a bag collection.  A java.util.Map can be mapped with <map>, preserving key and value  pairs. Use a java.util.HashMap to initialize a property.  A java.util.SortedMap can be mapped with <map> element, and the sort attribute can be set to either a comparator or natural ordering for in-memory sorting. Initialize the collection with a java.util.TreeMap instance. © JBoss, Inc. 2003, 2004. 24
  • 25. Mapping a set Professional Open Source™  The simplest implementation is a Set of String image filenames. First, add a collection property to the Item class: © JBoss, Inc. 2003, 2004. 25
  • 26. Professional Open Source™  The image filenames are stored in a table named ITEM_IMAGE, the collection table. From the point of view of the database, this table is a separate entity, a separate table, but Hibernate hides this for you.  The <key> element declares the foreign key column in the collection table that references the primary key ITEM_ID of the owning entity. The <element> tag declares this collection as a collection of value type instances—in this case, of strings.  A set can’t contain duplicate elements, so the primary key of the ITEM_IMAGE collection table is a composite of both columns in the <set> declaration: ITEM_ID and FILENAME. © JBoss, Inc. 2003, 2004. 26
  • 27. Disadvantages of <set> Professional Open Source™  A set is very inefficient if/when adding to a large collection, because Hibernate has to load the entire collection into memory in order to ensure that uniqueness is preserved. © JBoss, Inc. 2003, 2004. 27
  • 28. Mapping an identifier bag Professional Open Source™  An unordered collection that permits duplicate elements is called a bag.  Curiously, the Java Collections framework doesn’t include a bag implementation.However, the java.util.Collection interface has bag semantics, so you only need a matching implementation.  Write the collection property with the java.util.Collection interface,  and, on declaration, initialize it with an ArrayList of the JDK. Map the  collection in Hibernate with a standard <bag> or <idbag> element.  Hibernate has a built-in PersistentBag that can deal with lists; however, consistent with the contract of a bag, it ignores the position of elements in the ArrayList. In other words, you get a persistent Collection. © JBoss, Inc. 2003, 2004. 28
  • 29. Professional Open Source™ You also have to modify the collection table to permit duplicate FILENAMEs; the table needs a different primary key. An <idbag> mapping adds a surrogate key column to the collection table, much like the synthetic identifiers you use for entity classes. Note that the native generator for primary keys isn’t supported for <idbag> mappings © JBoss, Inc. 2003, 2004. 29
  • 30. Mapping a list Professional Open Source™  If you wish to preserve the order in which images are attached to the Item, u can use list © JBoss, Inc. 2003, 2004. 30
  • 31. Professional Open Source™  A <list> mapping requires the addition of an index column to the collection table.  The index column defines the position of the element in the collection. Thus,Hibernate is able to preserve the ordering of the collection elements.  The primary key of the collection table is a composite of ITEM_ID and POSITION.  Notice that duplicate elements (FILENAME) are now allowed, © JBoss, Inc. 2003, 2004. 31
  • 32. Mapping a map Professional Open Source™ The primary key of the collection table is a composite of ITEM_ID and IMAGENAME. The IMAGENAME column holds the keys of the map. Again, duplicate elements are allowed; © JBoss, Inc. 2003, 2004. 32
  • 33. Sorted and ordered collections Professional Open Source™ A sorted collection is sorted in memory using a Java comparator. An ordered collection is ordered at the database level using an SQL query with an order by clause. © JBoss, Inc. 2003, 2004. 33
  • 34. Professional Open Source™  By specifying sort="natural", you tell Hibernate to use a SortedMap and to sort the image names according to the compareTo() method of java.lang.String. If you need some other sort algorithm (for example, reverse alphabetical order),you may specify the name of a class that implements java.util.Comparator in the sort attribute. For example: © JBoss, Inc. 2003, 2004. 34
  • 35. Sorting Sets Professional Open Source™ © JBoss, Inc. 2003, 2004. 35
  • 36. Ordering Collections Professional Open Source™  Instead of switching to the Sorted* interfaces and the (Tree*  implementations), you may want to work with a linked map and to sort elements on the database side, not in memory. © JBoss, Inc. 2003, 2004. 36
  • 37. Ordering Map Professional Open Source™  The expression in the order-by attribute is a fragment of an SQL order by clause. In this case, Hibernate orders the collection elements by the IMAGENAME column in ascending order during loading of the collection. You can even include an SQL function call in the order-by attribute: © JBoss, Inc. 2003, 2004. 37
  • 38. Ordering Set Professional Open Source™ © JBoss, Inc. 2003, 2004. 38
  • 39. Ordering idbag Professional Open Source™ © JBoss, Inc. 2003, 2004. 39
  • 40. Collections of components Professional Open Source™ As you can see from the composition association style (the black diamond), Image is a component of Item, and Item is the entity that is responsible for the lifecycle of Image instances. The multiplicity of the association further declares this association as many- valued—that is, many (or zero) Image instances for the same Item instance. © JBoss, Inc. 2003, 2004. 40
  • 41. Mapping Collection of Components Professional Open Source™  Collections of components are mapped similarly to collections of JDK value type. The only difference is the use of <composite-element> instead of an <element> tag. An ordered set of images (internally, a LinkedHashSet) can be mapped like this: See next page for example data © JBoss, Inc. 2003, 2004. 41
  • 42. Professional Open Source™  The tables with example data are shown in figure This is a set, so the primary key of the collection table is a composite of the key column and all element columns: ITEM_ID, IMAGENAME, FILENAME, SIZEX, andSIZEY. Because these columns all appear in the primary key, you needed to declare them with not-null="true" (or make sure they’re NOT NULL in any existing schema). No column in a composite primary key can be nullable— you can’t identify what you don’t know. This is probably a disadvantage of this particular mapping. © JBoss, Inc. 2003, 2004. 42
  • 43. Avoiding not-null columns Professional Open Source™  Analogous to the additional surrogate identifier property an <idbag> offers, a surrogate key column would come in handy now. © JBoss, Inc. 2003, 2004. 43