Hibernate with hbm.xml Mapping

Hibernate DB Mapping File

Hibernate DB mapping file maps a Java persistence class to its DB definition

  • It is used before Hibernate annotation is introduced
    • Hibernate annotation allows developer to write the mapping definition in the same Java persistence class instead of a separate XML file
  • Information provided in this page is for legacy purpose and Hibernate annotation are recommended for new projects


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping package="com.innotrekker.app.hbm">
    <class name="Order" table="orders">
        <id name="id" column="o_id">
            <generator class="native"/>
        <property name="comment" column="o_comment"/>
        <property name="publishDate" type="timestamp" column="o_time"/>

  • The attribute package combined with the name forms the full Java class name of the corresponding persistence class: com.innotrekker.app.hbm.Order
    <hibernate-mapping package="com.innotrekker.app.hbm">
        <class name="Order" ...>
  • The sample declares a DB table orders with 3 columns o_id, o_comment and o_time
  • Declare the primary key
    <id name="id" column="o_id">
      <generator class="native"/>
    • Hibernate strongly recommends a primary key for every table
    • native request Hibernate to use the native DB sequence generator to generate the primary key
  • Property maps the persistence class getter and setter method to a DB Column
    <property name="comment" column="o_comment"/>
    entity.setComment("My Comment");
    • column defines the name of the DB column mapped to
    • If the attribute column is missing, the DB column name has the same value in the attribute name
      <property name="comment" />
  • Map the DB column type
    • Automatically, Hibernate derives the DB column type from the type used by the corresponding persistence class instance variable
    • When ambiguity occurs, for example java.util.Date may map to DB types DATE/TIME/TIMESTAMP, we clarify the intended Hibernate DB column type in the mapping

    • Hibernate mapping types translate between Java and SQL data types
    • However, most primary Java type will map automatically to the corresponding DB Type
      java.util.Date getPublishDate();
      <property name="publishDate" type="timestamp" column="o_time"/>
  • By default, Hibernate persistence class's instance variables are NOT persistent to DB until it is also defined in the mapping file