XML Mapping

Overview

Each mapping document starts with the tag

<hibernate-mapping ... >

This tag can include multiple mappings. Though I think that it is cleaner to have a separate XML per entity.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="de.laliluna.cachetest">
  <class name="Computer" table="tcomputer">
........ snip .......
  </class>
  <class name="Developer" table="tdeveloper">
........ snip .......
  </class>
</hibernate-mapping>

Field mapping

Each field, which should be stored, need to be added to the XML. You need to specify the field name and the type if it cannot be determined by Hibernate.

<class name="Player">
    <id name="id">
        <generator class="native"/>
    </id>
    <property name="birthDay" type="date"/>
    <property name="name" />

</class>

The field birthDay is of type java.util.Date. Hibernate cannot determine if you want to store a date, time or timestamp value. Therefor you need to specify the type. For a date field the following types are available: date, time, timestamp.

Java’s date time is mutable which renders it useless for many use cases. In addition it provides you with features like January is 0. For many years know there are plans to replace date in Java but since Java 7 does not appear, the date will not appear as well. You might consider to use a better date implementation like Joda Time.

If you treat your date as immutable, you can take advantage of Hibernate optimisations. Change your type to imm_date, imm_time or imm_timestamp and Hibernate will treat it as immutable as well. You need to take car that in your code, you will never change individual fields of a date but create a new instance and assign it to your entity.

// Good immutable usage
Calendar c = new GregorianCalendar();
c.setTime(john.getBirthDay());
c.add(Calendar.HOUR_OF_DAY, 1);
john.setBirthDay(c.getTime());

// Bad usage
john.getBirthDay().setHours(22);

There are additional attributes which allow to specify field length, not null or unique constraints. The access type can be specified as well. By default XML based mappings use the getter and setter to write fields, but you can change the approach per field.

<property name="name" length="20" column="player_name" not-null="true" unique="true" access="field"/>

Enum types cannot be persisted out of the box. You need to implement a UserType. Have a look in the Hibernate Reference for a description on writing user types.

The following table shows attributes you can set. The default behaviour is displayed as bold text. Very useful or important settings are marked with color. You only have to define properties which change the default behaviour. Most of the following is rarely needed.

<hibernate-mapping>

schema="schemaName"
The default database schema used for all mappings. You can overwrite the value per class. PostgreSql supports schemas.
catalog="catalogName"
The default database catalog used for all mappings. You can overwrite the value per class. Informix and MSSQL supports catalogs
default-cascade="none | all | save-update | delete | all-delete-orphan | delete-orphan"
Default cascading behaviour for relations. I prefer to leave this value and to define this explicitly in the relations.
default-access="field | property | myPropertyAccessorClass"
Default strategy used for accessing properties. Standard is property and you should keep this normally. This will use getters and setters to access fields. Field will access a property directly by its name. So your variables must be public. You can invent further methods with your own implementation of the interface org.hibernate.property.PropertyAccessor
default-lazy="true|false"
Default behaviour for loading of relations. You should leave this to true. More information on lazy loading can be found in chapter Lazy Initialization Lazy initialization
auto-import="true|false"
Allows use of unqualified class names in the query language for classes in this mapping. In most cases you appreciate this behaviour. Instead of from de.laliluna.example.Car c where c.color='blue' you can write from Car c where c.color='blue'
package="package.name"
Defines a package prefix for all class names in this mapping. This saves a lot of typing work when your classes are all in the same package.

Class mapping

The following table gives an overview of all tags available. Most of them are rarely needed. I have marked the most common tags with colour.

<class>

name="ClassName"
Name of the class or entity, Optional if you don’t want to change the entity name,
table="tableName"
Optional, default value is the class name. This is the name of mapped database table.
discriminator-value="discriminator_value"
This is used for inheritance mapping. Have a look at chapter Inheritance Mapping to read more about this. The value is used to distinguish sub classes. Acceptable values include null.
mutable="true|false"
Allows to define readonly classes. It can be used in combination with readonly cache which gives a lightning fast mapping. For performance tuning you could think of individual mappings for read only access.
schema="owner"
The database schema used for this class. This overwrites the default value. PostgreSql and other databases support schemas.
catalog="catalog"
The database catalog used for this class. This overwrites the default value. Informix, MSSQL and other databases support catalogs
proxy="ProxyInterface"
This is in my opinion only needed in special cases. You can define an interface used for lazy initialising proxies. Read more about this in the Hibernate reference. Search for proxy.
dynamic-update="true|false"
Normally update queries are prepared during the initialisation of Hibernate. If set to true, Hibernate will generate the SQL at runtime and include only changed properties. This is by far slower but useful when you use blobs fields in your mapping or if you want to allow concurrent updates to the same row. Concurrent updates = Two threads update the same row. This can work when different fields are changed. It can be used in combination with a special optimistic locking configuration.
dynamic-insert="true|false"
Same as for dynamic-update. Only difference is that in the insert statements only not null fields are included.
select-before-update="true|false"
Slows down performance and should not be used without a good reason. If true, Hibernate should never perform an SQL update unless it is certain that an object is actually modified. This is useful in case when you reattach objects and you do not want an update statement to be called in order to prevent that a trigger is called.
polymorphism="implicit|explicit"
Should only be changed with a good reason. Implicit means that a query of a super class of the mapped class will return this class. Explicit is useful when you have the normal class and a lightweight class not including all the fields. Then a query of the super class would not include the lightweight class when it is set to explicit.
where="arbitrary sql where condition"
Defines a condition always added when you retrieve objects of this class. It is useful when you want to hide data. For example the status 0 defines deleted data then you could use where="status <> 0"
persister="myPersisterClass"
Should only be changed with a good reason. A persister is responsible for writing the data. You could create a custom persister to save data to LDAP, a flat file, … In the Hibernate download you can find an example in the test directory org.hibernate.test.legacy.CustomPersister
batch-size="1"
Very interesting for tuning in special situations. Can be any number but should be reasonable. When you iterate through a list of 10 Book objects and call book.getAuthor than Hibernate will generate ten queries to fetch the author. A batch size of 4 would lead to 3 queries fetching 4,4 and 2 authors. If you use older Oracle versions and the class contains Blob/Clob you may be forced to use a batch-size of 1.
optimistic-lock="none | version | dirty | all"
Defines the optimistic locking strategy. The hibernate reference recommends strongly version. All would check all columns, dirty would check only changed columns. This would allow concurrent updates when the fields are not the same. Read more about optimistic locking in chapter TODO: Referenz nicht gefunden.
lazy="true|false"
You can disable lazy fetching of relations. Use this with care. Read more about this in chapter Hibernate Architecture
entity-name="EntityName"
Entity name is the name used in all queries. The default value is the class name. You do not have to set it. You can map the same class to multiple tables using different entity names. A special use case is the mapping to XML or Maps instead of classes. Read more about XML mapping and dynamic mapping in the Hibernate reference in the chapter dynamic models and XML mapping.
check="arbitrary sql check condition"
Can be used to check that a column only contains special values. For example you have an address table containing billing and delivery addresses. A type column contains either billing or delivery An example can be found in chapter Typed relation
rowid="rowid"
A rowID is the physical position of data. This is used for example in Orcale and speeds up update performance. Oracle only.
subselect="SQL expression"
Allows to generate views even if your database does not support it. You can define a complex select statement and map the resulting columns to the class. This can only be used with readonly mappings ⇒ mutable="false"
abstract="true|false"
Abstract means that in an inheritance mapping using union-subclass this class needs no corresponding table. Only subclasses objects are generated. You will understand this, when you read more about inheritance mapping. Read more about this in chapter Inheritance Mapping
node="element-name"
Only needed for XML mapping. Read more about this in the Hibernate Reference in chapter XML Mapping.

Other mapping tags

This book does include a reference of Hibernate annotations but not yet a complete reference of XML mappings. We have examples for the most common mapping situations in the next chapters. If you need a overview of all mapping tags, have a look in the Hibernate Reference provided with the Hibernate download. The chapter Mapping declaration describes the XML mappings completely.