06 association of value types

290 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
290
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

06 association of value types

  1. 1. Professional Open Source™ Association Mappings© JBoss, Inc. 2003, 2004. 07/17/04 1
  2. 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. 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. 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. 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. 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. 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. 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. 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. 10. Selecting a key Generator Professional Open Source™  Hibernate has several built-in identifier-generation strategies.© JBoss, Inc. 2003, 2004. 10
  11. 11. Professional Open Source™© JBoss, Inc. 2003, 2004. 11
  12. 12. Professional Open Source™© JBoss, Inc. 2003, 2004. 12
  13. 13. Professional Open Source™© JBoss, Inc. 2003, 2004. 13
  14. 14. Professional Open Source™© JBoss, Inc. 2003, 2004. 14
  15. 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. 16. Professional Open Source™ CLASS MAPPING OPTIONS© JBoss, Inc. 2003, 2004. 16
  17. 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. 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. 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. 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. 21. Declaring a package name Professional Open Source™© JBoss, Inc. 2003, 2004. 21
  22. 22. Mapping components Professional Open Source™  See the composition example.© JBoss, Inc. 2003, 2004. 22
  23. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 35. Sorting Sets Professional Open Source™© JBoss, Inc. 2003, 2004. 35
  36. 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. 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. 38. Ordering Set Professional Open Source™© JBoss, Inc. 2003, 2004. 38
  39. 39. Ordering idbag Professional Open Source™© JBoss, Inc. 2003, 2004. 39
  40. 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. 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. 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. 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

×