Mapping Types in Hibernate
Mapping Types in Hibernate
Hibernate maps Java data types into databases. Java type can be mapped into one or more column in database. We can set
Object's record as primitive types like int , byte or more complex for example java.util.Currency.
1.Primitive types.
This section will explain how to write the mapping documents manually. Although there are tools available to create these
mapping documents, learning how to create these documents manually helps in fine tuning and setting up advance table mapping.
Mapping Declaration
Object/relational mappings are usually defined in XML document. The mapping language is Java-centric, meaning that
mappings are constructed around persistent class declarations, not table declarations.
Mapping Document
<?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="org.somepackage.eg">
<class name="Foo" table=”FooTable”>
<id name="id" type=”java.lang.Long”>
<generator class=”sequence”/>
</id>
</class>
</hibernate-mapping>
The above example shows a typical mapping document that contains class mapping with table.
All mapping XML document should refer to hibernate-mapping-3.0.dtd via doctype.
<hibernate-mapping> element
The root element of hibernate mapping document is <hibernate-mapping> element. 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.
<hibernate-mapping
schema="schemaName" (1)
catalog="catalogName" (2)
default-cascade="cascade_style" (3)
default-access="field|property|ClassName" (4)
default-lazy="true|false" (5)
auto-import="true|false" (6)
package="package.name" (7)
/>
(1) schema (optional): The name of a database schema.
(2) catalog (optional): The name of a database catalog.
(3) default-cascade (optional - defaults to none): A default cascade style.
(4) default-access (optional - defaults to property): The strategy Hibernate should use for accessing all properties. Can be a
custom implementation of PropertyAccessor.
(5) default-lazy (optional - defaults to true): The default value for unspecifed lazy attributes of class and collection mappings.
(6) auto-import (optional - defaults to true): Specifies whether we can use unqualified class names (of classes in this
mapping) in the query language.
(7)
package (optional): Specifies a package prefix to assume for unqualified class names in the mapping document.
The <Class> element maps the domain object with corresponding entity in the database. hibernate-mapping element allows you
to nest several persistent <class> mappings, as shown above. It is however good practice to map only a single persistent class in
one mapping file and name it after the persistent superclass, e.g. User.hbm.xml, Group.hbm.xml.
<class
name="ClassName" (1)
table="tableName" (2)
discriminator-value="discriminator_value" (3)
mutable="true|false" (4)
schema="owner" (5)
catalog="catalog" (6)
proxy="ProxyInterface" (7)
dynamic-update="true|false" (8)
dynamic-insert="true|false" (9)
select-before-update="true|false" (10)
polymorphism="implicit|explicit" (11)
where="arbitrary sql where condition" (12)
persister="PersisterClass" (13)
batch-size="N" (14)
optimistic-lock="none|version|dirty|all" (15)
lazy="true|false" (16)
entity-name="EntityName" (17)
catalog="catalog" (18)
check="arbitrary sql check condition" (19)
rowid="rowid" (20)
subselect="SQL expression" (21)
abstract="true|false" (22)
/>
(1) 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.
(2) table (optional - defaults to the unqualified class name): The name of its database table.
(3) 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.
(4) mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable.
(5) schema (optional): Override the schema name specified by the root <hibernate-mapping> element.
(6) catalog (optional): Override the catalog name specified by the root <hibernate-mapping> element.
(7)
proxy (optional): Specifies an interface to use for lazy initializing proxies. You may specify the name of the class itself.
(8) dynamic-update (optional, defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain
only those columns whose values have changed.
(9) 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.
(10) 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.
(11)
polymorphism (optional, defaults to implicit): Determines whether implicit or explicit query polymorphism is used.
(12)
where (optional) specify an arbitrary SQL WHERE condition to be used when retrieving objects of this class
(13)
persister (optional): Specifies a custom ClassPersister.
(14)
batch-size (optional, defaults to 1) specify a "batch size" for fetching instances of this class by identifier.
(15)
optimistic-lock (optional, defaults to version): Determines the optimistic locking strategy.
(16)
lazy (optional): Lazy fetching may be completely disabled by setting lazy="false".
(17) entity-name (optional): Hibernate3 allows a class to be mapped multiple times (to different tables, potentially), and
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. See Section 4.4, “Dynamic models” for more information.
(18)
catalog (optional): The name of a database catalog used for this class and its table.
(19)
check (optional): A SQL expression used to generate a multi-row check constraint for automatic schema generation.
(20) 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.
(21) 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.
(22)
abstract (optional): Used to mark abstract superclasses in <union-subclass> hierarchies.
<id> element
The <id> element defines the mapping from that property to the primary key column. 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.
<id
name="propertyName" (1)
type="typename" (2)
column="column_name" (3)
unsaved-value="null|any|none|undefined|id_value" (4)
access="field|property|ClassName"> (5)
<generator class="generatorClass"/>
/>
<property> element
The <property> element declares a persistent, JavaBean style property of the class.
<property
name="propertyName" (1)
column="column_name" (2)
type="typename" (3)
update="true|false" (4)
insert="true|false" (4)
formula="arbitrary SQL expression" (5)
access="field|property|ClassName" (6)
lazy="true|false" (7)
unique="true|false" (8)
not-null="true|false" (9)
optimistic-lock="true|false" (10)
/>
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:
(1) name: the name of the property, with an initial lowercase letter.
(2) 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).
(3) type (optional): a name that indicates the Hibernate type.
(4) 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.
(5) formula (optional): an SQL expression that defines the value for a computed property. Computed properties do not have a
column mapping of their own.
(6) access (optional - defaults to property): The strategy Hibernate should use for accessing the property value.
(7) 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).
(8) unique (optional): Enable the DDL generation of a unique constraint for the columns. Also, allow this to be the target of a
property-ref.
(9)
not-null (optional): Enable the DDL generation of a nullability constraint for the columns.
(10) 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, determines if a version increment should occur when 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).
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:
<property name="totalPrice"
formula="( SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p
WHERE li.productId = p.productId
AND li.customerId = customerId
AND li.orderNumber = orderNumber )"/>
<many-to-one> element
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" (1)
column="column_name" (2)
class="ClassName" (3)
cascade="cascade_style" (4)
fetch="join|select" (5)
update="true|false" (6)
insert="true|false" (6)
property-ref="propertyNameFromAssociatedClass" (7)
access="field|property|ClassName" (8)
unique="true|false" (9)
not-null="true|false" (10)
optimistic-lock="true|false" (11)
lazy="true|false" (12)
entity-name="EntityName"
/>
(9) 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. This makes the association multiplicity effectively one to one.
(10)
not-null (optional): Enable the DDL generation of a nullability constraint for the foreign key columns.
(11) 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, dertermines if a version increment should occur when this property is dirty.
(12) 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).
A typical many-to-one declaration looks as simple as this:
<one-to-one> element
<one-to-one
name="propertyName" (1) (1)
class="ClassName" (2) (2)
cascade="cascade_style" (3) (3)
constrained="true|false" (4) (4)
fetch="join|select" (5) (5)
property-ref="propertyNameFromAssociatedClass" (6) (6)
access="field|property|ClassName" (7) (7)
formula="any SQL expression" (8) (8)
entity-name="EntityName"
/>
(8) formula (optional): Almost all one to one associations map to the primary key of the owning entity. In the rare case that
this is not the case, you may specify a some other column, columns or expression to join on using an SQL formula. (See
org.hibernate.test.onetooneformula for an example.)
A typical many-to-one declaration looks as simple as this:
<one-to-one> element
<one-to-one
name="propertyName" (1) (1)
class="ClassName" (2) (2)
cascade="cascade_style" (3) (3)
constrained="true|false" (4) (4)
fetch="join|select" (5) (5)
property-ref="propertyNameFromAssociatedClass" (6) (6)
access="field|property|ClassName" (7) (7)
formula="any SQL expression" (8) (8)
entity-name="EntityName"
/>
(8) formula (optional): Almost all one to one associations map to the primary key of the owning entity. In the rare case that
this is not the case, you may specify a some other column, columns or expression to join on using an SQL formula. (See
org.hibernate.test.onetooneformula for an example.)
A typical many-to-one declaration looks as simple as this: