- In O/R mapping you need to map with java type, such as String, Long, and Integer, to the SQL data types such as Varchar, char, and date.
- The two mapping types must be mapped, connected , or matched to each other.
- It means that a data type of a POJO class property must be matched with the same data type of a column in a database table.
- Object/relational mappings are usually 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 and not table declarations.
-
Please note that even though many Hibernate users choose to write the XML by hand, a number of tools exist to generate the mapping document.
-
These include XDoclet, Middlegen and AndroMDA.
Here is an example of mapping:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="eg">
<class name="Cat" table="cats" discriminator-value="C">
<id name="id">
<generator class="native"/>
</id>
<discriminator column="subclass" type="character"/>
<property name="weight"/>
<property name="birthdate" type="date" not-null="true" update="false"/>
<property name="color" type="eg.types.ColorUserType" not-null="true"
update="false"/>
<property name="sex" not-null="true" update="false"/>
<property name="litterId" column="litterId" update="false"/>
<many-to-one name="mother" column="mother_id" update="false"/>
<set name="kittens" inverse="true" order-by="litter_id">
<key column="mother_id"/>
<one-to-many class="Cat"/>
</set>
<subclass name="DomesticCat" discriminator-value="D">
<property name="name" type="string"/>
</subclass>
</class>
<class name="Dog">
<!-- mapping for Dog could go here -->
</class>
</hibernate-mapping>
-
We will discuss the content of the mapping document.
-
We will only describe, however, 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).
- All XML mappings should declare the doctype shown. The actual DTD can 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.
- If you experience lookups of the DTD using an Internet connection, check the DTD declaration against the contents of your classpath.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
EntityResolver
- Hibernate will first attempt to resolve DTDs in its classpath.
-
It does this is by registering a custom org.xml.sax.EntityResolver implementation with the SAXReader it uses to read in the xml files.
-
This custom EntityResolver recognizes two different systemId namespaces:
-
1) a hibernate namespace is recognized whenever the resolver encounters a systemId starting with http://hibernate.sourceforge.net/. The resolver attempts to resolve these entities via the classloader which loaded the Hibernate classes.
2)a user namespace is recognized whenever the resolver encounters a systemId using a classpath:// URL protocol. The resolver will attempt to resolve these entities via (1) the current thread context classloader and (2) the classloader which loaded the Hibernate classes.
The following is an example of utilizing user namespacing:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
[ <!ENTITY types SYSTEM "classpath://your/domain/types.xml"> ]>
<hibernate-mapping package="your.domain">
<class name="MyEntity">
<id name="id" type="my-custom-id-type"> ... </id>
</class>
</hibernate-mapping>
Where types.xml is a resource in the your.domain package and contains a custom typedef.
- 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 they are specified, tablenames will be qualified by the given schema and catalog names.
-
If they are missing, tablenames will be unqualified.
-
The default-cascade attribute specifies what cascade style should be assumed for properties and collections that do not specify a cascade attribute.
-
By default, the auto-import attribute allows you to use unqualified class names in the query language.
<hibernate-mapping
schema="schemaName"
catalog="catalogName"
default-cascade="cascade_style"
default-access="field|property|ClassName"
default-lazy="true|false"
auto-import="true|false"
package="package.name" />
-
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. It can be a custom implementation of PropertyAccessor.
-
default-lazy (optional defaults to true) : the default value for unspecified 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 use 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”.
-
An exception will result if you attempt to assign two classes to the same “imported” name.
-
The hibernate-mapping element allows you to nest several persistent <class> mappings, as shown above.
-
It is, however, good practice (and expected by some tools) to map only a single persistent class, or a single class hierarchy, in one mapping file and name it after the persistent superclass.
-
For example, Cat.hbm.xml, Dog.hbm.xml, or if using inheritance, Animal.hbm.xml.
You can declare a persistent class using the class element.
For example
<class name="ClassName"
table="tableName"
discriminator-value="discriminator_value"
mutable="true|false"
schema="owner"
catalog="catalog"
proxy="ProxyInterface"
dynamic-update="true|false"
dynamic-insert="true|false"
select-before-update="true|false"
polymorphism="implicit|explicit"
where="arbitrary sql where condition"
persister="PersisterClass"
batch-size="N"
optimistic-lock="none|version|dirty|all"
lazy="true|false"
entity-name="EntityName"
check="arbitrary sql check condition"
rowclass="nrowid"
subselect="SQL expression"
abstract="true|false"
node="element-name" />
-
name (optional) : the fully qualified Java class name of the persistent class or interface. If this attribute is missing, it is assumed that the mapping is for a non-POJO entity.
-
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 distinguishes individual subclasses that is used for polymorphic behavior. Acceptable values include null and not null.
-
mutable (optional – defaults to true) : specifies that instances of the class are (not) mutable.
-
schema (optional) : overrides the schema name specified by the root <hibernate-mapping> element.
-
catalog (optional): overrides the catalog name specified by the root <hibernate-mapping> element.
-
proxy (optional) : specifies an interface to use for lazy initializing proxies. You can specify the name of the class itself.
-
dynamic-update (optional – defaults to false) : specifies that UPDATE SQL should be generated at runtime and can 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. Only when a transient object has been associated with a new session using update(), will Hibernate 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) : specifies 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) : specifies 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 can be disabled by setting lazy=”false”.
-
entity-name (optional – defaults to the class name) : Hibernate3 allows a class to be mapped multiple times, potentially to different tables. It also allows entity mappings that are represented by Maps or XML at the Java level. In these cases, you should provide an explicit arbitrary name for the entity.
-
check (optional) : an SQL expression used to generate a multi-row check constraint for automatic schema generation.
-
rowid (optional) : Hibernate can use ROWIDs on databases. On Oracle, for example, Hibernate can use the rowid extra column for fast updates once this option has been set 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. This is useful if you want to have a view instead of a base table. See below for more information.
-
abstract (optional) : is used to mark abstract superclasses in <union-subclass> hierarchies.
- It is acceptable for the named persistent class to be an interface.
-
You can declare implementing classes of that interface using the <subclass> element.
-
You can persist any static inner class. Specify the class name using the standard form i.e. e.g.Foo$Bar.
-
Immutable classes, mutable=”false”, cannot be updated or deleted by the application. This allows Hibernate to make some minor performance optimizations.
-
There is no difference between a view and a base table for a Hibernate mapping.
-
This is transparent at the database level, although some DBMS do not support views properly, especially with updates.
-
Sometimes you want to use a view, but you cannot create one in the database (i.e. with a legacy schema).
-
In this case, you can map an immutable and read-only entity to a given SQL subselect expression:
- 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.
<id
name="propertyName"
type="typename"
column="column_name"
unsaved-value="null|any|none|undefined|id_value"
access="field|property|ClassName">
node="element-name|@attribute-name|element/@attribute|."
<generator class="generatorClass"/>
</id>
-
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 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 almost never needed in Hibernate3.
-
There is an alternative <composite-id> declaration that allows access to legacy data with composite keys.
-
Its use is strongly discouraged for anything else.
-
The optional <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.
<id name="id" type="long" column="cat_id">
<generator class="org.hibernate.id.TableHiLoGenerator">
<param name="table">uid_table</param>
<param name="column">next_hi_value_column</param>
</generator>
</id>
- All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface.
-
Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations.
The shortcut names for the built-in generators are as follows:
-
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.
-
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 that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.
-
guid
uses a database-generated GUID string on MS SQL Server and MySQL.
-
native
selects identity, sequence or hilo depending upon the capabilities of the underlying database.
-
assigned
lets the application assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.
-
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. It is usually used in conjunction with a <one-to-one> primary key association.
-
sequence-identity
a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution.This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.
- It is for composite key.
A table with a composite key can be mapped with 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.
<composite-id name="propertyName" class="ClassName" mapped="true|false" access="field|property|ClassName" node="element-name|.">
<key-property name="propertyName" type="typename" column="column_name"/>
<key-many-to-one name="propertyName class="ClassName" column="column_name"/>
......
</composite-id>
The following attributes are used to specify a mapped composite identifier:
-
mapped (optional – defaults to false) : indicates that a mapped composite identifier is used, and that the contained property mappings refer to both the entity class and the composite identifier class.
-
class (optional – but required for a mapped composite identifier): the class used as a composite identifier.
-
name (optional – required for this approach) : a property of component type that holds the composite identifier. Please see chapter 9 for more information.
-
access (optional – defaults to property) : the strategy Hibernate uses for accessing the property value.
-
class (optional – defaults to the property type determined by reflection) : the component class used as a composite identifier. Please see the next section for more information.
The third approach, an identifier component, is recommended for almost all applications.
- The <discriminator> element is required for polymorphic persistence using the table-per-class-hierarchy mapping strategy.
-
It 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 can be used: string, character, integer, byte, short, boolean, yes_no, true_false.
<discriminator
column="discriminator_column"
type="discriminator_type"
force="true|false"
insert="true|false"
formula="arbitrary sql expression"
/>
-
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) : “forces” Hibernate to specify the 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. It tells Hibernate not to include the column in SQL INSERTs.
-
formula (optional) : an arbitrary SQL expression that is executed when a type has to be evaluated. It allows content-based discrimination.
- The <version> element is optional and indicates that the table contains versioned data.
This is particularly useful if you plan to use long transactions.
Here is more information:
<version
column="version_column"
name="propertyName"
type="typename"
access="field|property|ClassName"
unsaved-value="null|negative|undefined"
generated="never|always"
insert="true|false"
node="element-name|@attribute-name|element/@attribute|."
/>
-
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 uses to access 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.
-
generated (optional – defaults to never) : specifies that this version property value is generated by the database. See the discussion of generated properties for more information.
-
insert (optional – defaults to true) : specifies whether the version column should be included in SQL insert statements. It can be set to false if the database column is defined with a default value of 0.
- The optional <timestamp> element indicates that the table contains timestamped data.
-
This provides an alternative to versioning.
-
Timestamps are a less safe implementation of optimistic locking.
-
However, sometimes the application might use the timestamps in other ways.
<timestamp
column="timestamp_column"
name="propertyName"
access="field|property|ClassName"
unsaved-value="null|undefined"
source="vm|db"
generated="never|always"
node="element-name|@attribute-name|element/@attribute|."
/>
-
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 uses 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.
-
source (optional – defaults to vm): Where should Hibernate retrieve the timestamp value from? From the database, or from the current JVM? Database-based timestamps incur an overhead because Hibernate must hit the database in order to determine the “next value”. It is safer to use in clustered environments. Not all Dialects are known to support the retrieval of the database’s current timestamp. Others may also be unsafe for usage in locking due to lack of precision (Oracle 8, for example).
-
generated (optional – defaults to never) : specifies that this timestamp property value is actually generated by the database. See the discussion of generated properties for more information.
The <property> element declares a persistent JavaBean style property of the class.
<property
name="propertyName"
column="column_name"
type="typename"
update="true|false"
insert="true|false"
formula="arbitrary SQL expression"
access="field|property|ClassName"
lazy="true|false"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
generated="never|insert|always"
node="element-name|@attribute-name|element/@attribute|."
index="index_name"
unique_key="unique_key_id"
length="L"
precision="P"
scale="S"
/>
-
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 can 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 column(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 uses 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. It requires build-time bytecode instrumentation.
-
unique (optional) : enables the DDL generation of a unique constraint for the columns. Also, allow this to be the target of a property-ref.
-
not-null (optional) : enables 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, it determines if a version increment should occur when this property is dirty.
-
generated (optional – defaults to never) : specifies that this property value is actually generated by the database. See the discussion of generated properties for more information.
- An ordinary association to another persistent class is declared using a many-to-one element.
-
The relational model is a many-to-one association; a foreign key in one table is referencing the primary key column(s) of the target table.
<many-to-one
name="propertyName"
column="column_name"
class="ClassName"
cascade="cascade_style"
fetch="join|select"
update="true|false"
insert="true|false"
property-ref="propertyNameFromAssociatedClass"
access="field|property|ClassName"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"
lazy="proxy|no-proxy|false"
not-found="ignore|exception"
entity-name="EntityName"
formula="arbitrary SQL expression"
node="element-name|@attribute-name|element/@attribute|."
embed-xml="true|false"
index="index_name"
unique_key="unique_key_id"
foreign-key="foreign_key_name"
/>
-
name : the name of the property.
-
column (optional) : the name of the foreign key column. This can 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.
-
fetch (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 another property that maps to the same column(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 uses for accessing the property value.
-
unique (optional) : enables the DDL generation of a unique constraint for the foreign-key column. By allowing this to be the target of a property-ref, you can make the association multiplicity one-to-one.
-
not-null (optional) : enables 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, it determines if a version increment should occur when this property is dirty.
-
lazy (optional – defaults to proxy) : by default, single point associations are proxied. lazy=”no-proxy” specifies that the property should be fetched lazily when the instance variable is first accessed.
- This requires build-time bytecode instrumentation. lazy=”false” specifies that the association will always be eagerly fetched.
-
not-found (optional – defaults to exception) : specifies how foreign keys that reference missing rows will be handled. ignore will treat a missing row as a null association.
-
entity-name (optional) : the entity name of the associated class.
-
formula (optional) : an SQL expression that defines the value for a computed foreign key.
A one-to-one association to another persistent class is declared using a one-to-one element.
<one-to-one
name="propertyName"
class="ClassName"
cascade="cascade_style"
constrained="true|false"
fetch="join|select"
property-ref="propertyNameFromAssociatedClass"
access="field|property|ClassName"
formula="any SQL expression"
lazy="proxy|no-proxy|false"
entity-name="EntityName"
node="element-name|@attribute-name|element/@attribute|."
embed-xml="true|false"
foreign-key="foreign_key_name"
/>
-
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 and references the table of the associated class.
-
This option affects the order in which save() and delete() are cascaded, and determines whether the association can be proxied. It 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 uses for accessing the property value.
-
formula (optional) : almost all one-to-one associations map to the primary key of the owning entity. If this is not the case, you can specify another column, columns or expression to join on using an SQL formula. See org.hibernate.test.onetooneformula for an example.
-
lazy (optional – defaults to proxy) : by default, single point associations are proxied. lazy=”no-proxy” specifies that the property should be fetched lazily when the instance variable is first accessed.
-
It requires build-time bytecode instrumentation. lazy=”false” specifies that the association will always be eagerly fetched.
Note that if constrained=”false”, proxying is impossible and Hibernate will eagerly fetch the association.
-
entity-name (optional) : the entity name of the associated class.
- The <component> element maps properties of a child object to columns of the table of a parent class.
-
Components can, in turn, declare their own properties, components or collections.
“Component” examples as below:
<component
name="propertyName"
class="className"
insert="true|false"
update="true|false"
access="field|property|ClassName"
lazy="true|false"
optimistic-lock="true|false"
unique="true|false"
node="element-name|.">
<property ...../>
<many-to-one .... />
........
</component>
-
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 uses 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. It requires build-time bytecode instrumentation.
-
optimistic-lock (optional – defaults to true) : specifies that updates to this component either do or do not require acquisition of the optimistic lock. It determines if a version increment should occur when this property is dirty.
-
unique (optional – defaults to false) : specifies that a unique constraint exists upon all mapped columns of the component.
Properties
- The <properties> element allows the definition of a named, logical grouping of the properties of a class.
-
The most important use of the construct is that it allows a combination of properties to be the target of a property-ref. It is also a convenient way to define a multi-column unique constraint.
For example:
<properties
name="logicalName"
insert="true|false"
update="true|false"
optimistic-lock="true|false"
unique="true|false">
<property ...../>
<many-to-one .... />
........
</properties>
-
name : the logical name of the grouping. It is not an actual property name.
-
insert : do the mapped columns appear in SQL INSERTs?
-
update : do the mapped columns appear in SQL UPDATEs?
-
optimistic-lock (optional – defaults to true) : specifies that updates to these properties either do or do not require acquisition of the optimistic lock. It determines if a version increment should occur when these properties are dirty.
-
unique (optional – defaults to false) : specifies that a unique constraint exists upon all mapped columns of the component.
-
Polymorphic persistence requires the declaration of each subclass of the root persistent class.
-
For the table-per-class-hierarchy mapping strategy, the <subclass> declaration is used.
For example:
<subclass
name="ClassName"
discriminator-value="discriminator_value"
proxy="ProxyInterface"
lazy="true|false"
dynamic-update="true|false"
dynamic-insert="true|false"
entity-name="EntityName"
node="element-name"
extends="SuperclassName">
<property .... />
.....
</subclass>
-
name : the fully qualified class name of the subclass.
-
discriminator-value (optional – defaults to the class name) : a value that distinguishes individual subclasses.
-
proxy (optional) : specifies a class or interface used for lazy initializing proxies.
-
lazy (optional – defaults to true) : setting lazy=”false” disables the use of lazy fetching.
-
Each subclass can also be mapped to its own table.
-
This is called the table-per-subclass mapping strategy.
-
An inherited state is retrieved by joining with the table of the superclass.
-
To do this you use the <joined-subclass> element.
<joined-subclass
name="ClassName"
table="tablename"
proxy="ProxyInterface"
lazy="true|false"
dynamic-update="true|false"
dynamic-insert="true|false"
schema="schema"
catalog="catalog"
extends="SuperclassName"
persister="ClassName"
subselect="SQL expression"
entity-name="EntityName"
node="element-name">
<key .... >
<property .... />
.....
</joined-subclass>
-
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.
- A third option is to map only the concrete classes of an inheritance hierarchy to tables.
-
This is called the table-per-concrete-class strategy. Each table defines all persistent states of the class, including the inherited state.
-
In Hibernate, it is not necessary to explicitly map such inheritance hierarchies.
-
You can map each class with a separate <class> declaration.
-
However, if you wish use polymorphic associations (e.g. an association to the superclass of your hierarchy), you need to use the <union-subclass> mapping. For example:
<union-subclass
name="ClassName"
table="tablename"
proxy="ProxyInterface"
lazy="true|false"
dynamic-update="true|false"
dynamic-insert="true|false"
schema="schema"
catalog="catalog"
extends="SuperclassName"
abstract="true|false"
persister="ClassName"
subselect="SQL expression"
entity-name="EntityName"
node="element-name">
<property .... />
.....
</union-subclass>
-
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.
Using the <join> element, it is possible to map properties of one class to several tables that have a one-to-one relationship.
<join
table="tablename"
schema="owner"
catalog="catalog"
fetch="join|select"
inverse="true|false"
optional="true|false">
<key ... />
<property ... />
...
</join>
-
table : the name of the joined table.
-
schema (optional) : overrides the schema name specified by the root <hibernate-mapping> element.
-
catalog (optional): overrides the catalog name specified by the root <hibernate-mapping> element.
-
fetch (optional – defaults to join) : if set to join, the default, Hibernate will use an inner join to retrieve a <join> defined by a class or its superclasses. It will use an outer join for a <join> defined by a subclass. If set to select then Hibernate will use a sequential select for a <join> defined on a subclass. This will be issued only if a row represents an instance of the subclass. Inner joins will still be used to retrieve a <join> defined by the class and its superclasses.
-
inverse (optional – defaults to false) : if enabled, Hibernate will not 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. It will always use an outer join to retrieve the properties.
- The <key> element has featured a few times within this guide.
-
It appears anywhere the parent mapping element defines a join to a new table that references the primary key of the original table.
-
It also defines the foreign key in the joined table:
<key
column="columnname"
on-delete="noaction|cascade"
property-ref="propertyName"
not-null="true|false"
update="true|false"
unique="true|false"
/>
-
column (optional) : the name of the foreign key column. This can 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.
-
vproperty-ref (optional): specifies that the foreign key refers to columns that are not the primary key of the original table. It is provided for legacy data.
-
not-null (optional) : specifies that the foreign key columns are not nullable. This is implied whenever the foreign key is also part of the primary key.
-
update (optional) : specifies that the foreign key should never be updated. This is implied whenever the foreign key is also part of the primary key.
-
unique (optional) : specifies that the foreign key should have a unique constraint. This is implied whenever the foreign key is also the primary key.
- Mapping elements which accept a column attribute will alternatively accept a <column> subelement.
-
Likewise, <formula> is an alternative to the formula attribute.
For example:
<column name="column_name"
length="N"
precision="N"
scale="N"
not-null="true|false"
unique="true|false"
unique-key="multicolumn_unique_key_name"
index="index_name"
sql-type="sql_type_name"
check="SQL expression"
default="SQL expression"/>
<formula>SQL expression</formula>
column and formula attributes can even be combined within the same property or association mapping to express,for example, exotic join conditions.
<many-to-one name="homeAddress" class="Address" insert="false" update="false">
<column name="person_id" not-null="true" length="10"/>
<formula>'MAILING'</formula>
</many-to-one>
Recent Comments