06 association of value types

43
Professional Open Source™ © JBoss, Inc. 2003, 2004. 1 07/17/04 Association Mappings

Upload: thirumuru2012

Post on 18-Dec-2014

149 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: 06 association of value types

Professional Open Source™

© JBoss, Inc. 2003, 2004. 1

07/17/04

Association Mappings

Page 2: 06 association of value types

Professional Open Source™

© JBoss, Inc. 2003, 2004. 2

07/17/04

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

Fine Grained Domain models

Page 3: 06 association of value types

© JBoss, Inc. 2003, 2004. 3

Professional Open Source™

Collections of Value types

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.

Page 4: 06 association of value types

© JBoss, Inc. 2003, 2004. 4

Professional Open Source™

ValueType Vs Entity

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

Page 5: 06 association of value types

© JBoss, Inc. 2003, 2004. 5

Professional Open Source™

Understanding Java identity and equality

There are three methods for identifying objects:

1. 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.

2. 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.

Page 6: 06 association of value types

© JBoss, Inc. 2003, 2004. 6

Professional Open Source™

Handling database identity

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.

Page 7: 06 association of value types

© JBoss, Inc. 2003, 2004. 7

Professional Open Source™

Selecting a primary key

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.

Page 8: 06 association of value types

© JBoss, Inc. 2003, 2004. 8

Professional Open Source™

Natural Key

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.

Page 9: 06 association of value types

© JBoss, Inc. 2003, 2004. 9

Professional Open Source™

Surrogate Key

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.

Page 10: 06 association of value types

© JBoss, Inc. 2003, 2004. 10

Professional Open Source™

Selecting a key Generator

Hibernate has several built-in identifier-generation strategies.

Page 11: 06 association of value types

© JBoss, Inc. 2003, 2004. 11

Professional Open Source™

Page 12: 06 association of value types

© JBoss, Inc. 2003, 2004. 12

Professional Open Source™

Page 13: 06 association of value types

© JBoss, Inc. 2003, 2004. 13

Professional Open Source™

Page 14: 06 association of value types

© JBoss, Inc. 2003, 2004. 14

Professional Open Source™

Page 15: 06 association of value types

© JBoss, Inc. 2003, 2004. 15

Professional Open Source™

Configuring a generator

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>

Page 16: 06 association of value types

© JBoss, Inc. 2003, 2004. 16

Professional Open Source™

CLASS MAPPING OPTIONS

Page 17: 06 association of value types

© JBoss, Inc. 2003, 2004. 17

Professional Open Source™

Dynamic SQL generation

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:

Page 18: 06 association of value types

© JBoss, Inc. 2003, 2004. 18

Professional Open Source™

Making an entity immutable

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.

Page 19: 06 association of value types

© JBoss, Inc. 2003, 2004. 19

Professional Open Source™

Naming entities for querying

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:

Page 20: 06 association of value types

© JBoss, Inc. 2003, 2004. 20

Professional Open Source™

Naming entities for querying

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.

Page 21: 06 association of value types

© JBoss, Inc. 2003, 2004. 21

Professional Open Source™

Declaring a package name

Page 22: 06 association of value types

© JBoss, Inc. 2003, 2004. 22

Professional Open Source™

Mapping components

See the composition example.

Page 23: 06 association of value types

© JBoss, Inc. 2003, 2004. 23

Professional Open Source™

Selecting a collection interface

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.

Page 24: 06 association of value types

© JBoss, Inc. 2003, 2004. 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.

Page 25: 06 association of value types

© JBoss, Inc. 2003, 2004. 25

Professional Open Source™

Mapping a set

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

Page 26: 06 association of value types

© JBoss, Inc. 2003, 2004. 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.

Page 27: 06 association of value types

© JBoss, Inc. 2003, 2004. 27

Professional Open Source™

Disadvantages of <set>

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.

Page 28: 06 association of value types

© JBoss, Inc. 2003, 2004. 28

Professional Open Source™

Mapping an identifier bag

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.

Page 29: 06 association of value types

© JBoss, Inc. 2003, 2004. 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 surrogatekey column to the collection table, much like the synthetic identifiers you use forentity classes.Note that the native generator for primary keys isn’t supported for <idbag> mappings

Page 30: 06 association of value types

© JBoss, Inc. 2003, 2004. 30

Professional Open Source™

Mapping a list

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

Page 31: 06 association of value types

© JBoss, Inc. 2003, 2004. 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,

Page 32: 06 association of value types

© JBoss, Inc. 2003, 2004. 32

Professional Open Source™

Mapping a map

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;

Page 33: 06 association of value types

© JBoss, Inc. 2003, 2004. 33

Professional Open Source™

Sorted and ordered collections

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.

Page 34: 06 association of value types

© JBoss, Inc. 2003, 2004. 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:

Page 35: 06 association of value types

© JBoss, Inc. 2003, 2004. 35

Professional Open Source™

Sorting Sets

Page 36: 06 association of value types

© JBoss, Inc. 2003, 2004. 36

Professional Open Source™

Ordering Collections

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.

Page 37: 06 association of value types

© JBoss, Inc. 2003, 2004. 37

Professional Open Source™

Ordering Map

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:

Page 38: 06 association of value types

© JBoss, Inc. 2003, 2004. 38

Professional Open Source™

Ordering Set

Page 39: 06 association of value types

© JBoss, Inc. 2003, 2004. 39

Professional Open Source™

Ordering idbag

Page 40: 06 association of value types

© JBoss, Inc. 2003, 2004. 40

Professional Open Source™

Collections of components

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.

Page 41: 06 association of value types

© JBoss, Inc. 2003, 2004. 41

Professional Open Source™

Mapping Collection of Components

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

Page 42: 06 association of value types

© JBoss, Inc. 2003, 2004. 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 thekey column and all element columns: ITEM_ID, IMAGENAME, FILENAME, SIZEX, andSIZEY.

Because these columns all appear in the primary key, you needed todeclare 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.

Page 43: 06 association of value types

© JBoss, Inc. 2003, 2004. 43

Professional Open Source™

Avoiding not-null columns

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