Basic O/R Mapping
Mapping declaration
Object/relational mappings are defined in an XML document. The mapping document
is designed to be readable and hand-editable. The mapping language is Java-centric,
meaning that mappings are constructed around persistent class declarations, not
table declarations.
Note that, even though many Hibernate users choose to write the XML by hand,
a number of tools exist to generate the mapping document, including XDoclet,
Middlegen and AndroMDA.
Lets kick off with an example mapping:
]]>
We will now discuss the content of the mapping document. We will only describe the
document elements and attributes that are used by Hibernate at runtime. The mapping
document also contains some extra optional attributes and elements that affect the
database schemas exported by the schema export tool. (For example the
not-null attribute.)
Doctype
All XML mappings should declare the doctype shown. The actual DTD may be found
at the URL above, in the directory hibernate-x.x.x/src/org/hibernate
or in hibernate3.jar. Hibernate will always look for
the DTD in its classpath first.
hibernate-mapping
This element has several optional attributes. The schema and
catalog attributes specify that tables referred to in this mapping
belong to the named schema and/or catalog. If specified, tablenames will be qualified
by the given schema and catalog names. If missing, tablenames will be unqualified.
The default-cascade attribute specifies what cascade style
should be assumed for properties and collections which do not specify a
cascade attribute. The auto-import attribute lets us
use unqualified class names in the query language, by default.
]]>
schema (optional): The name of a database schema.
catalog (optional): The name of a database catalog.
default-cascade (optional - defaults to none):
A default cascade style.
default-access (optional - defaults to property):
The strategy Hibernate should use for accessing all properties. Can be a custom
implementation of PropertyAccessor.
default-lazy (optional - defaults to true):
The default value for unspecifed lazy attributes of class and
collection mappings.
auto-import (optional - defaults to true):
Specifies whether we can use unqualified class names (of classes in this mapping)
in the query language.
package (optional): Specifies a package prefix to assume for
unqualified class names in the mapping document.
If you have two persistent classes with the same (unqualified) name, you should set
auto-import="false". Hibernate will throw an exception if you attempt
to assign two classes to the same "imported" name.
class, dynamic-class
You may declare a persistent class using the class element:
]]>
name: The fully qualified Java class name of the persistent class
(or interface).
table (optional - defaults to the unqualified class name): The
name of its database table.
discriminator-value (optional - defaults to the class name): A value
that distiguishes individual subclasses, used for polymorphic behaviour. Acceptable
values include null and not null.
mutable (optional, defaults to true): Specifies
that instances of the class are (not) mutable.
schema (optional): Override the schema name specified by
the root <hibernate-mapping> element.
catalog (optional): Override the catalog name specified by
the root <hibernate-mapping> element.
proxy (optional): Specifies an interface to use for lazy
initializing proxies. You may specify the name of the class itself.
dynamic-update (optional, defaults to false):
Specifies that UPDATE SQL should be generated at runtime and
contain only those columns whose values have changed.
dynamic-insert (optional, defaults to false):
Specifies that INSERT SQL should be generated at runtime and
contain only the columns whose values are not null.
select-before-update (optional, defaults to false):
Specifies that Hibernate should never perform an SQL UPDATE
unless it is certain that an object is actually modified. In certain cases (actually, only
when a transient object has been associated with a new session using update()),
this means that Hibernate will perform an extra SQL SELECT to determine
if an UPDATE is actually required.
polymorphism (optional, defaults to implicit):
Determines whether implicit or explicit query polymorphism is used.
where (optional) specify an arbitrary SQL WHERE
condition to be used when retrieving objects of this class
persister (optional): Specifies a custom ClassPersister.
batch-size (optional, defaults to 1) specify a "batch size"
for fetching instances of this class by identifier.
optimistic-lock (optional, defaults to version):
Determines the optimistic locking strategy.
lazy (optional): Lazy fetching may be completely disabled by setting
lazy="false".
entity-name (optional): Hibernate3 supports class-less persistence:
use the <dynamic-class> instead of a <class>
mapping and an entity-name attribute instead of a class name. This
allows you to implement your domain model using maps of maps or any other dynamic
approach. See for more information.
catalog (optional): The name of a database catalog used for this
class and its table.
check (optional): A SQL expression used to generate a multi-row
check constraint for automatic schema generation.
rowid (optional): Hibernate can use so called ROWIDs on databases
which support. E.g. on Oracle, Hibernate can use the rowid extra
column for fast updates if you set this option to rowid. A ROWID
is an implementation detail and represents the physical location of a stored tuple.
subselect (optional): Maps an immutable and read-only entity
to a database subselect. Useful if you want to have a view instead of a base table,
but don't. See below for more information.
abstract (optional): Used to mark abstract superclasses in
<union-subclass> hierarchies.
It is perfectly acceptable for the named persistent class to be an interface. You would then
declare implementing classes of that interface using the <subclass>
element. You may persist any static inner class. You should specify the
class name using the standard form ie. eg.Foo$Bar.
Immutable classes, mutable="false", may not be updated or deleted by the
application. This allows Hibernate to make some minor performance optimizations.
The optional proxy attribute enables lazy initialization of persistent
instances of the class. Hibernate will initially return CGLIB proxies which implement
the named interface. The actual persistent object will be loaded when a method of the
proxy is invoked. See "Proxies for Lazy Initialization" below.
Implicit polymorphism means that instances of the class will be returned
by a query that names any superclass or implemented interface or the class and that instances
of any subclass of the class will be returned by a query that names the class itself.
Explicit polymorphism means that class instances will be returned only
be queries that explicitly name that class and that queries that name the class will return
only instances of subclasses mapped inside this <class> declaration
as a <subclass> or <joined-subclass>. For
most purposes the default, polymorphism="implicit", is appropriate.
Explicit polymorphism is useful when two different classes are mapped to the same table
(this allows a "lightweight" class that contains a subset of the table columns).
The persister attribute lets you customize the persistence strategy used for
the class. You may, for example, specify your own subclass of
org.hibernate.persister.EntityPersister or you might even provide a
completely new implementation of the interface
org.hibernate.persister.ClassPersister that implements persistence via,
for example, stored procedure calls, serialization to flat files or LDAP. See
org.hibernate.test.CustomPersister for a simple example (of "persistence"
to a Hashtable).
Note that the dynamic-update and dynamic-insert
settings are not inherited by subclasses and so may also be specified on the
<subclass> or <joined-subclass> elements.
These settings may increase performance in some cases, but might actually decrease
performance in others. Use judiciously.
Use of select-before-update will usually decrease performance. It is very
useful to prevent a database update trigger being called unnecessarily if you reattach a
graph of detached instances to a Session.
If you enable dynamic-update, you will have a choice of optimistic
locking strategies:
version check the version/timestamp columns
all check all columns
dirty check the changed columns, allowing some concurrent updates
none do not use optimistic locking
We very strongly recommend that you use version/timestamp
columns for optimistic locking with Hibernate. This is the optimal strategy with
respect to performance and is the only strategy that correctly handles modifications
made to detached instances (ie. when Session.merge() is used).
There is no difference between a view and a base table for a Hibernate mapping, as
expected this is transparent at the database level (note that some DBMS don't support
views properly, especially with updates). Sometimes you want to use a view, but can't
create one in the database (ie. with a legacy schema). In this case, you can map an
immutable and read-only entity to a given SQL subselect expression:
select id, name as ident, address as loc, 'human' as species from humans
union
select id, ident, planet as loc, species from aliens
...]]>
Declare the tables to synchronize this entity, to ensure that auto-flush happens
correctly, and that queries against the derived entity do not return stale data.
The <subselect> is available as both an attribute and
a nested mapping element.
id
Mapped classes must declare the primary key column of the database
table. Most classes will also have a JavaBeans-style property holding the unique identifier
of an instance. The <id> element defines the mapping from that
property to the primary key column.
]]>
name (optional): The name of the identifier property.
type (optional): A name that indicates the Hibernate type.
column (optional - defaults to the property name): The
name of the primary key column.
unsaved-value (optional - defaults to a "sensible" value):
An identifier property value that indicates that an instance is newly instantiated
(unsaved), distinguishing it from detached instances that were saved or loaded
in a previous session.
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
If the name attribute is missing, it is assumed that the class has no
identifier property.
The unsaved-value attribute is important! If the identfier property of your
class does not default to the normal Java default value (null or zero), then you should specify
the actual default.
There is an alternative <composite-id> declaration to allow access to
legacy data with composite keys. We strongly discourage its use for anything else.
generator
The required <generator> child element names a Java class used
to generate unique identifiers for instances of the persistent class. If any parameters
are required to configure or initialize the generator instance, they are passed using the
<param> element.
uid_table
next_hi_value_column
]]>
All generators implement the interface org.hibernate.id.IdentifierGenerator.
This is a very simple interface; some applications may choose to provide their own specialized
implementations. However, Hibernate provides a range of built-in implementations. There are shortcut
names for the built-in generators:
increment
generates identifiers of type long, short or
int that are unique only when no other process is inserting data
into the same table.
Do not use in a cluster.
identity
supports identity columns in DB2, MySQL, MS SQL Server, Sybase and
HypersonicSQL. The returned identifier is of type long,
short or int.
sequence
uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator
in Interbase. The returned identifier is of type long,
short or int
hilo
uses a hi/lo algorithm to efficiently generate identifiers of
type long, short or int,
given a table and column (by default hibernate_unique_key and
next_hi respectively) as a source of hi values. The hi/lo algorithm
generates identifiers that are unique only for a particular database. Do not
use this generator with connections enlisted with JTA or with a user-supplied
connection.
seqhilo
uses a hi/lo algorithm to efficiently generate identifiers of type
long, short or int,
given a named database sequence.
uuid
uses a 128-bit UUID algorithm to generate identifiers of type string,
unique within a network (the IP address is used). The UUID is encoded
as a string of hexadecimal digits of length 32.
guid
uses a database-generated GUID string on MS SQL Server and MySQL.
native
picks identity, sequence or
hilo depending upon the capabilities of the
underlying database.
assigned
lets the application to assign an identifier to the object before
save() is called.
select
retrieves a primary key assigned by a database trigger by selecting
the row by some unique key and retrieving the primary key value.
foreign
uses the identifier of another associated object. Usually used in conjunction
with a <one-to-one> primary key association.
Hi/lo algorithm
The hilo and seqhilo generators provide two alternate
implementations of the hi/lo algorithm, a favorite approach to identifier generation. The
first implementation requires a "special" database table to hold the next available "hi" value.
The second uses an Oracle-style sequence (where supported).
hi_value
next_value
100
]]>
hi_value
100
]]>
Unfortunately, you can't use hilo when supplying your own
Connection to Hibernate, or when Hibernate is using an application
server datasource to obtain connections enlisted with JTA. Hibernate must be able to
fetch the "hi" value in a new transaction. A standard approach in an EJB environment is
to implement the hi/lo algorithm using a stateless session bean.
UUID algorithm
The UUID contains: IP address, startup time of the JVM (accurate to a quarter
second), system time and a counter value (unique within the JVM). It's not
possible to obtain a MAC address or memory address from Java code, so this is
the best we can do without using JNI.
Identity columns and sequences
For databases which support identity columns (DB2, MySQL, Sybase, MS SQL), you
may use identity key generation. For databases that support
sequences (DB2, Oracle, PostgreSQL, Interbase, McKoi, SAP DB) you may use
sequence style key generation. Both these strategies require
two SQL queries to insert a new object.
person_id_sequence
]]>
]]>
For cross-platform development, the native strategy will
choose from the identity, sequence and
hilo strategies, dependant upon the capabilities of the
underlying database.
Assigned identifiers
If you want the application to assign identifiers (as opposed to having
Hibernate generate them), you may use the assigned generator.
This special generator will use the identifier value already assigned to the
object's identifier property. This generator is used when the primary key
is a natural key instead of a surrogate key.
Choosing the assigned generator makes Hibernate use
unsaved-value="undefined", forcing Hibernate to go to
the database to determine if an instance is transient or detached, unless
there is a version or timestampe property, or you define
Interceptor.isUnsaved().
Primary keys assigned by triggers
For legacy schemas only (Hibernate does not generate DDL with triggers).
socialSecurityNumber
]]>
In the above example, there is a unique valued property named
socialSecurityNumber defined by the class, as a
natural key, and a surrogate key named person_id
whose value is generated by a trigger.
composite-id
......
]]>
For a table with a composite key, you may map multiple properties of the class
as identifier properties. The <composite-id> element
accepts <key-property> property mappings and
<key-many-to-one> mappings as child elements.
]]>
Your persistent class must override equals()
and hashCode() to implement composite identifier equality. It must
also implements Serializable.
Unfortunately, this approach to composite identifiers means that a persistent object
is its own identifier. There is no convenient "handle" other than the object itself.
You must instantiate an instance of the persistent class itself and populate its
identifier properties before you can load() the persistent state
associated with a composite key. We will describe a much more
convenient approach where the composite identifier is implemented as a seperate class
in . The attributes described below apply only
to this alternative approach:
name (optional): A property of component type that holds the
composite identifier (see next section).
class (optional - defaults to the property type determined by
reflection): The component class used as a composite identifier (see next section).
unsaved-value (optional - defaults to undefined):
Indicates that transient instances should be considered newly instantiated, if set
to any, or detached, if set to none. It is best
to leave the default value in all cases.
discriminator
The <discriminator> element is required for polymorphic persistence
using the table-per-class-hierarchy mapping strategy and declares a discriminator column of the
table. The discriminator column contains marker values that tell the persistence layer what
subclass to instantiate for a particular row. A restricted set of types may be used:
string, character, integer,
byte, short, boolean,
yes_no, true_false.
]]>
column (optional - defaults to class) the
name of the discriminator column.
type (optional - defaults to string) a
name that indicates the Hibernate type
force (optional - defaults to false)
"force" Hibernate to specify allowed discriminator values even when retrieving
all instances of the root class.
insert (optional - defaults to true)
set this to false if your discriminator column is also part
of a mapped composite identifier. (Tells Hibernate to not include the column
in SQL INSERTs.)
formula (optional) an arbitrary SQL expression that is
executed when a type has to be evaluated. Allows content-based discrimination.
Actual values of the discriminator column are specified by the
discriminator-value attribute of the <class> and
<subclass> elements.
The force attribute is (only) useful if the table contains rows with
"extra" discriminator values that are not mapped to a persistent class. This will not
usually be the case.
Using the formula attribute you can declare an arbitrary SQL expression
that will be used to evaluate the type of a row:
]]>
version (optional)
The <version> element is optional and indicates that
the table contains versioned data. This is particularly useful if you plan to
use long transactions (see below).
]]>
column (optional - defaults to the property name): The name
of the column holding the version number.
name: The name of a property of the persistent class.
type (optional - defaults to integer):
The type of the version number.
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
unsaved-value (optional - defaults to undefined):
A version property value that indicates that an instance is newly instantiated
(unsaved), distinguishing it from detached instances that were saved or loaded
in a previous session. (undefined specifies that the identifier
property value should be used.)
Version numbers may be of type long, integer,
short, timestamp or calendar.
A version or timestamp property should never be null for a detached instance, so
Hibernate will detact any instance with a null version or timestamp as transient,
no matter what other unsaved-value strategies are specified.
Declaring a nullable version or timestamp property is an easy way to avoid
any problems with transitive reattachment in Hibernate, especially useful for people
using assigned identiifers or composite keys!
timestamp (optional)
The optional <timestamp> element indicates that the table contains
timestamped data. This is intended as an alternative to versioning. Timestamps are by nature
a less safe implementation of optimistic locking. However, sometimes the application might
use the timestamps in other ways.
]]>
column (optional - defaults to the property name): The name
of a column holding the timestamp.
name: The name of a JavaBeans style property of
Java type Date or Timestamp of the
persistent class.
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
unsaved-value (optional - defaults to null):
A version property value that indicates that an instance is newly instantiated
(unsaved), distinguishing it from detached instances that were saved or loaded
in a previous session. (undefined specifies that the identifier
property value should be used.)
Note that <timestamp> is equivalent to
<version type="timestamp">.
property
The <property> element declares a persistent, JavaBean style
property of the class.
]]>
name: the name of the property, with an initial lowercase
letter.
column (optional - defaults to the property name): the name
of the mapped database table column. This may also be specified by nested
<column> element(s).
type (optional): a name that indicates the Hibernate type.
update, insert (optional - defaults to true) :
specifies that the mapped columns should be included in SQL UPDATE
and/or INSERT statements. Setting both to false
allows a pure "derived" property whose value is initialized from some other
property that maps to the same colum(s) or by a trigger or other application.
formula (optional): an SQL expression that defines the value for a
computed property. Computed properties do not have a column
mapping of their own.
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
lazy (optional - defaults to false): Specifies
that this property should be fetched lazily when the instance variable is first
accessed (requires build-time bytecode instrumentation).
unique (optional): Enable the DDL generation of a unique
constraint for the columns. Also, allow this to be the target of
a property-ref.
not-null (optional): Enable the DDL generation of a nullability
constraint for the columns.
optimistic-lock (optional - defaults to true):
Specifies that updates to this property do or do not require acquisition of the
optimistic lock. In other words, define if a version check should be made if this
property is dirty.
typename could be:
The name of a Hibernate basic type (eg. integer, string, character,
date, timestamp, float, binary, serializable, object, blob).
The name of a Java class with a default basic type (eg. int, float,
char, java.lang.String, java.util.Date, java.lang.Integer, java.sql.Clob).
The name of a serializable Java class.
The class name of a custom type (eg. com.illflow.type.MyCustomType).
If you do not specify a type, Hibernate will use reflection upon the named
property to take a guess at the correct Hibernate type. Hibernate will try to
interpret the name of the return class of the property getter using rules 2, 3,
4 in that order. However, this is not always enough.
In certain cases you will still need the type
attribute. (For example, to distinguish between Hibernate.DATE and
Hibernate.TIMESTAMP, or to specify a custom type.)
The access attribute lets you control how Hibernate will access
the property at runtime. By default, Hibernate will call the property get/set pair.
If you specify access="field", Hibernate will bypass the get/set
pair and access the field directly, using reflection. You may specify your own
strategy for property access by naming a class that implements the interface
org.hibernate.property.PropertyAccessor.
An especially powerful feature are derived properties. These properties are by
definition read-only, the property value is computed at load time. You declare
the computation as a SQL expression, this translates to a SELECT
clause subquery in the SQL query that loads an instance:
]]>
Note that you can reference the entities own table by not declaring an alias on
a particular column (customerId in the given example). Also note
that you can use the nested <formula> mapping element
if you don't like to use the attribute.
many-to-one
An ordinary association to another persistent class is declared using a
many-to-one element. The relational model is a
many-to-one association. (Its really just an object reference.)
]]>
name: The name of the property.
column (optional): The name of the foreign key column.
This may also be specified by nested <column>
element(s).
class (optional - defaults to the property type
determined by reflection): The name of the associated class.
cascade (optional): Specifies which operations should
be cascaded from the parent object to the associated object.
join (optional - defaults to select):
Chooses between outer-join fetching or sequential select fetching.
update, insert (optional - defaults to true)
specifies that the mapped columns should be included in SQL UPDATE
and/or INSERT statements. Setting both to false
allows a pure "derived" association whose value is initialized from some other
property that maps to the same colum(s) or by a trigger or other application.
property-ref: (optional) The name of a property of the associated
class that is joined to this foreign key. If not specified, the primary key of
the associated class is used.
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
unique (optional): Enable the DDL generation of a unique
constraint for the foreign-key column. Also, allow this to be the target of
a property-ref.
not-null (optional): Enable the DDL generation of a nullability
constraint for the foreign key columns.
optimistic-lock (optional - defaults to true):
Specifies that updates to this property do or do not require acquisition of the
optimistic lock. In other words, define if a version check should be made if this
property is dirty.
The cascade attribute permits the following values:
all, save-update, delete,
none. Setting a value other than none
will propagate certain operations to the associated (child) object.
See "Lifecycle Objects" below.
A typical many-to-one declaration looks as simple as
]]>
The property-ref attribute should only be used for mapping legacy
data where a foreign key refers to a unique key of the associated table other than
the primary key. This is an ugly relational model. For example, suppose the
Product class had a unique serial number, that is not the primary
key. (The unique attribute controls Hibernate's DDL generation with
the SchemaExport tool.)
]]>
Then the mapping for OrderItem might use:
]]>
This is certainly not encouraged, however.
If the referenced unique key comprises multiple properties of the associated entity, you should
map the referenced properties inside a named <properties> element.
one-to-one
A one-to-one association to another persistent class is declared using a
one-to-one element.
]]>
name: The name of the property.
class (optional - defaults to the property type
determined by reflection): The name of the associated class.
cascade (optional) specifies which operations should
be cascaded from the parent object to the associated object.
constrained (optional) specifies that a foreign key constraint
on the primary key of the mapped table references the table of the associated
class. This option affects the order in which save() and
delete() are cascaded (and is also used by the schema export
tool).
fetch (optional - defaults to select):
Chooses between outer-join fetching or sequential select fetching.
property-ref: (optional) The name of a property of the associated class
that is joined to the primary key of this class. If not specified, the primary key of
the associated class is used.
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
There are two varieties of one-to-one association:
primary key associations
unique foreign key associations
Primary key associations don't need an extra table column; if two rows are related by
the association then the two table rows share the same primary key value. So if you want
two objects to be related by a primary key association, you must make sure that they
are assigned the same identifier value!
For a primary key association, add the following mappings to Employee and
Person, respectively.
]]>
]]>
Now we must ensure that the primary keys of related rows in the PERSON and
EMPLOYEE tables are equal. We use a special Hibernate identifier generation strategy
called foreign:
employee
...
]]>
A newly saved instance of Person is then assigned the same primar
key value as the Employee instance refered with the employee
property of that Person.
Alternatively, a foreign key with a unique constraint, from Employee to
Person, may be expressed as:
]]>
And this association may be made bidirectional by adding the following to the
Person mapping:
]]>
component, dynamic-component
The <component> element maps properties of a
child object to columns of the table of a parent class. Components may, in
turn, declare their own properties, components or collections. See
"Components" below.
........
]]>
name: The name of the property.
class (optional - defaults to the property type
determined by reflection): The name of the component (child) class.
insert: Do the mapped columns appear in SQL
INSERTs?
update: Do the mapped columns appear in SQL
UPDATEs?
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
lazy (optional - defaults to false): Specifies
that this component should be fetched lazily when the instance variable is first
accessed (requires build-time bytecode instrumentation).
optimistic-lock (optional - defaults to true):
Specifies that updates to this component do or do not require acquisition of the
optimistic lock. In other words, define if a version check should be made if this
property is dirty.
The child <property> tags map properties of the
child class to table columns.
The <component> element allows a <parent>
subelement that maps a property of the component class as a reference back to the
containing entity.
The <dynamic-component> element allows a Map
to be mapped as a component, where the property names refer to keys of the map.
subclass
Finally, polymorphic persistence requires the declaration of each subclass of
the root persistent class. For the (recommended) table-per-class-hierarchy
mapping strategy, the <subclass> declaration is used.
.....
]]>
name: The fully qualified class name of the subclass.
discriminator-value (optional - defaults to the class name): A
value that distiguishes individual subclasses.
proxy (optional): Specifies a class or interface to use for
lazy initializing proxies.
lazy (optional, defaults to true): Setting
lazy="false" disables the use of lazy fetching.
Each subclass should declare its own persistent properties and subclasses.
<version> and <id> properties
are assumed to be inherited from the root class. Each subclass in a heirarchy must
define a unique discriminator-value. If none is specified, the
fully qualified Java class name is used.
joined-subclass
Alternatively, each subclass may be mapped to its own table (table-per-subclass
mapping strategy). Inherited state is retrieved by joining with the table of the
superclass. We use the <joined-subclass> element.
.....
]]>
name: The fully qualified class name of the subclass.
table: The name of the subclass table.
proxy (optional): Specifies a class or interface to use
for lazy initializing proxies.
lazy (optional, defaults to true): Setting
lazy="false" disables the use of lazy fetching.
No discriminator column is required for this mapping strategy. Each subclass must,
however, declare a table column holding the object identifier using the
<key> element. The mapping at the start of the chapter
would be re-written as:
]]>
union-subclass
A third option is to map only the concrete classes of an inheritance hierarchy
to tables, (the table-per-concrete-class strategy) where each table defines all
persistent state of the class, including inherited state. In Hibernate, it is
not absolutely necessary to explicitly map such inheritance hierarchies. You
can simply map each class with a separate <class>
declaration. However, if you wish use polymorphic associations (e.g. an association
directed at the superclass of your hierarchy), you need to
use the <union-subclass> mapping.
.....
]]>
name: The fully qualified class name of the subclass.
table: The name of the subclass table.
proxy (optional): Specifies a class or interface to use
for lazy initializing proxies.
lazy (optional, defaults to true): Setting
lazy="false" disables the use of lazy fetching.
No discriminator column or key column is required for this mapping strategy.
join
Using the <join> element, it is possible to map
properties of one class to several tables.
...
]]>
table: The name of the joined table.
schema (optional): Override the schema name specified by
the root <hibernate-mapping> element.
catalog (optional): Override the catalog name specified by
the root <hibernate-mapping> element.
fetch (optional - defaults to join):
If set to select for a join defined on a subclass, then rather
than joining, a sequential select will be issued only if a row turns out to represent
an instance of the subclass.
inverse (optional - defaults to false):
If enabled, Hibernate will not try to insert or update the properties defined
by this join.
optional (optional - defaults to false):
If enabled, Hibernate will insert a row only if the properties defined by this
join are non-null .
For example, the address information for a person can be mapped to a separate
table (while preserving value type semantics for all properties):
...
...]]>
This feature is often only useful for legacy data models, we recommend fewer
tables than classes and a fine-grained domain model. However, it is useful
for switching between inheritance mapping strategies in a single hierarchy, as
explained later.
key
We've seen the <key> element crop up a few times
now. It appears anywhere the parent mapping element defines a join to
a new table, and defines the foreign key in the joined table, that references
the primary key of the original table.
]]>
column (optional): The name of the foreign key column.
This may also be specified by nested <column>
element(s).
on-delete (optional, defaults to noaction):
Specifies whether the foreign key constraint has database-level cascade delete
enabled.
property-ref (optional): Specifies that the foreign key refers
to columns that are not the primary key of the orginal table. (Provided for
legacy data.)
We recommend that for systems where delete performance is important, all keys should be
defined on-delete="cascade", and Hibernate will use a database-level
ON CASCADE DELETE constraint, instead of many individual
DELETE statements. Be aware that this feature bypasses Hibernate's
usual optimistic locking strategy for versioned data.
map, set, list, bag
Collections are discussed later.
import
Suppose your application has two persistent classes with the same name, and you don't want to
specify the fully qualified (package) name in Hibernate queries. Classes may be "imported"
explicitly, rather than relying upon auto-import="true". You may even import
classes and interfaces that are not explicitly mapped.
]]>
]]>
class: The fully qualified class name of of any Java class.
rename (optional - defaults to the unqualified class name):
A name that may be used in the query language.
Hibernate Types
Entities and values
To understand the behaviour of various Java language-level objects with respect
to the persistence service, we need to classify them into two groups:
An entity exists independently of any other objects holding
references to the entity. Contrast this with the usual Java model where an
unreferenced object is garbage collected. Entities must be explicitly saved and
deleted (except that saves and deletions may be cascaded
from a parent entity to its children). This is different from the ODMG model of
object persistence by reachablity - and corresponds more closely to how
application objects are usually used in large systems. Entities support
circular and shared references. They may also be versioned.
An entity's persistent state consists of references to other entities and
instances of value types. Values are primitives,
collections, components and certain immutable objects. Unlike entities, values
(in particular collections and components) are
persisted and deleted by reachability. Since value objects (and primitives) are
persisted and deleted along with their containing entity they may not be
independently versioned. Values have no independent identity, so they cannot be
shared by two entities or collections.
All Hibernate types except collections support null semantics.
Up until now, we've been using the term "persistent class" to refer to
entities. We will continue to do that. Strictly speaking, however, not all
user-defined classes with persistent state are entities. A
component is a user defined class with value semantics.
Basic value types
The basic types may be roughly categorized into
integer, long, short, float, double, character, byte,
boolean, yes_no, true_false
Type mappings from Java primitives or wrapper classes to appropriate
(vendor-specific) SQL column types. boolean, yes_no
and true_false are all alternative encodings for
a Java boolean or java.lang.Boolean.
string
A type mapping from java.lang.String to
VARCHAR (or Oracle VARCHAR2).
date, time, timestamp
Type mappings from java.util.Date and its subclasses
to SQL types DATE, TIME and
TIMESTAMP (or equivalent).
calendar, calendar_date
Type mappings from java.util.Calendar to
SQL types TIMESTAMP and DATE
(or equivalent).
big_decimal
A type mapping from java.math.BigDecimal to
NUMERIC (or Oracle NUMBER).
locale, timezone, currency
Type mappings from java.util.Locale,
java.util.TimeZone and
java.util.Currency
to VARCHAR (or Oracle VARCHAR2).
Instances of Locale and Currency are
mapped to their ISO codes. Instances of TimeZone are
mapped to their ID.
class
A type mapping from java.lang.Class to
VARCHAR (or Oracle VARCHAR2).
A Class is mapped to its fully qualified name.
binary
Maps byte arrays to an appropriate SQL binary type.
text
Maps long Java strings to a SQL CLOB or
TEXT type.
serializable
Maps serializable Java types to an appropriate SQL binary type. You
may also indicate the Hibernate type serializable with
the name of a serializable Java class or interface that does not default
to a basic type.
clob, blob
Type mappings for the JDBC classes java.sql.Clob and
java.sql.Blob. These types may be inconvenient for some
applications, since the blob or clob object may not be reused outside of
a transaction. (Furthermore, driver support is patchy and inconsistent.)
Unique identifiers of entities and collections may be of any basic type except
binary, blob and clob.
(Composite identifiers are also allowed, see below.)
The basic value types have corresponding Type constants defined on
org.hibernate.Hibernate. For example, Hibernate.STRING
represents the string type.
Custom value types
It is relatively easy for developers to create their own value types. For example,
you might want to persist properties of type java.lang.BigInteger
to VARCHAR columns. Hibernate does not provide a built-in type
for this. But custom types are not limited to mapping a property (or collection element)
to a single table column. So, for example, you might have a Java property
getName()/setName() of type
java.lang.String that is persisted to the columns
FIRST_NAME, INITIAL, SURNAME.
To implement a custom type, implement either org.hibernate.UserType
or org.hibernate.CompositeUserType and declare properties using the
fully qualified classname of the type. Check out
org.hibernate.test.DoubleStringType to see the kind of things that
are possible.
]]>
Notice the use of <column> tags to map a property to multiple
columns.
You may also supply parameters to a UserType in the mapping file. To do this, your UserType
has to implement the org.hibernate.usertype.ParameterizedType interface.
To supply parameters to your UserType, you can use the <type> element
in your mapping files.
1
]]>
The UserType can now retrieve the value for the parameter named default
from the Properties object passed to it.
If you use a certain UserType very often, it may be useful to define a shorter name for it.
You can do this using the <typedef> element in your mapping files.
Typedefs contain a UserType and a defined name for it, and may also contain a list of default
paramter values if the type defined implements ParameterizedType. After
defining the name, it can be used everywhere the original classname can be used.
2
]]>
It is also possible to override the parameters supplied in a typedef on a case-by-case basis
by using type parameters on the property mapping.
Even though Hibernate's rich range of built-in types and support for components means you
will very rarely need to use a custom type, it is nevertheless
considered good form to use custom types for (non-entity) classes that occur frequently
in your application. For example, a MonetoryAmount class is a good
candidate for a CompositeUserType, even though it could easily be mapped
as a component. One motivation for this is abstraction. With a custom type, your mapping
documents would be future-proofed against possible changes in your way of representing
monetory values.
Any type mappings
There is one further type of property mapping. The <any> mapping element
defines a polymorphic association to classes from multiple tables. This type of mapping always
requires more than one column. The first column holds the type of the associated entity.
The remaining columns hold the identifier. It is impossible to specify a foreign key constraint
for this kind of association, so this is most certainly not meant as the usual way of mapping
(polymorphic) associations. You should use this only in very special cases (eg. audit logs,
user session data, etc).
The meta-type attribute lets the application specify a custom type that
maps database column values to persistent classes which have identifier properties of the
type specified by id-type. You must specify the mapping from values of
the meta-type to class names.
]]>
.....
.....
]]>
name: the property name.
id-type: the identifier type.
meta-type (optional - defaults to string):
Any type that is allowed for a discriminator mapping.
cascade (optional- defaults to none):
the cascade style.
access (optional - defaults to property): The
strategy Hibernate should use for accessing the property value.
optimistic-lock (optional - defaults to true):
Specifies that updates to this property do or do not require acquisition of the
optimistic lock. In other words, define if a version check should be made if this
property is dirty.
SQL quoted identifiers
You may force Hibernate to quote an identifier in the generated SQL by enclosing the table or
column name in backticks in the mapping document. Hibernate will use the correct quotation
style for the SQL Dialect (usually double quotes, but brackets for SQL
Server and backticks for MySQL).
...
]]>
Modular mapping files
It is possible to define subclass, union-subclass,
and joined-subclass mappings in seperate mapping documents, directly beneath
hibernate-mapping. This allows you to extend a class hierachy just by adding
a new mapping file. You must specify an extends attribute in the subclass mapping,
naming a previously mapped superclass. Note: Previously this feature made the ordering of the mapping
documents important. Since Hibernate 3, the ordering of mapping files does not matter when using the
extends keyword. The ordering inside a single mapping file still needs to be defined as superclasses
before subclasses.
]]>
Using XDoclet markup
Many Hibernate users prefer to embed mapping information directly in sourcecode using
XDoclet @hibernate.tags. We will not cover this approach in this
document, since strictly it is considered part of XDoclet. However, we include the
following example of the Cat class with XDoclet mappings.
See the Hibernate web site for more examples of XDoclet and Hibernate.
Using JDK 5.0 Annotations
JDK 5.0 introduced XDoclet-style annotations at the language level, type-safe and
checked at compile time. This mechnism is more powerful than XDoclet annotations and
better supported by tools and IDEs. IntelliJ IDEA, for example, supports auto-completion
and syntax highlighting of JDK 5.0 annotations. The new revision of the EJB specification
(JSR-220) uses JDK 5.0 annotations as the primary metadata mechanism for entity beans.
Hibernate3 implements the EntityManager of JSR-220 (the persistence API),
support for mapping metadata is available via the Hibernate Annotations
package, as a separate download. Both EJB3 (JSR-220) and Hibernate3 metadata is supported.
Note that support for JDK 5.0 Annotations (and JSR-220) is still work in progress and
not completed.