Hibernate Mappings

Published: Wednesday, 28 July 2004

Mappings by example

Please refer to the official Hibernate documentation for a more in-depth explanation.

ID auto increment using a sequence

<class name="com.magicmonster.intranet.users.businessobjects.UserBO" table="users">
  <id name="id" type="long" column="id">
    <generator class="sequence">
      <param name="sequence">users_s</param>
    </generator>
  </id>
  <property name="password"/>
  <property name="username"/>
</class>

When a new user object is added to the user table, the users_s sequence is used for the id column.

Even though it is an integer in the database, we use type="long"

The UserBO JavaBean must have a Long object property.

Mapping a bean property to a different column name

If the bean’s property names are different to the table columns, you must use something like this:

<property name="startDate" column="start_date"/>
<property name="endDate" column="end_date"/>

startDate is the bean property, and start_date is the database table column

Mapping dates and time

Using hbm2ddl, to create the ddl from the hibernate xml configuration files, I ran into the problem of having a sql datatype of timestamp in postgresql, when the Java type is a Date.

The Java Date object contains information such as date, time, timezone, milliseconds. If you only need a plain date comprising of a day, month and year, then use the type attribute to specify the SQL datatype.

<property name="accountingDate" column="accounting_date" type="date"/>

If you don’t do this it defaults to a timestamp. When it did default to this, in postgresql it was a timestamp without a timezone, and hibernate tried to insert timezone information along with the timestamp.