Hibernate.org Community Documentation

- Prev
- Next

## Chapter 2. Tutorial Using Native Hibernate APIs and hbm.xml Mappings

This tutorial is located within the download bundle under `basic` and illustrates

- using Hibernate mapping files (hbm.xml) to provide mapping information

- using the native Hibernate APIs

## 2.1. The Hibernate configuration file

The resource file `hibernate.cfg.xml` defines Hibernate configuration information.

The `connection.driver_class`, `connection.url`, `connection.username` and `connection.password` `property` elements define JDBC connection information. These tutorials utilize the H2 in-memory database. So these are all specific to running H2 in its in-memory mode. `connection.pool_size` is used to configure Hibernate's built-in connection pool how many connections to pool.

## Important

The built-in Hibernate connection pool is in no way intended for production use. It lacks several features found on any decent connection pool. See the section discussion in Hibernate Developer Guide for further information.

The `dialect` property specifies the particular SQL variant Hibernate with which Hibernate will converse.

## Tip

In most cases, Hibernate is able to properly determine which dialect to use which is invaluable if your application targets multiple databases. This is discussed in detail in the Hibernate Developer Guide

The `hbm2ddl.auto` property turns on automatic generation of database schemas directly into the database.

Finally, add the mapping file(s) for persistent classes to the configuration. The `resource` attribute of the `mapping` element says to attempt to locate that mapping as a classpath resource (via a `java.lang.ClassLoader` lookup).

## 2.2. The entity Java class

The entity class for this tutorial is `org.hibernate.tutorial.hbm.Event`.

Notes About the Entity

- This class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields. Although this is the recommended design, it is not required.

- The no-argument constructor, which is also a JavaBean convention, is a requirement for all persistent classes. Hibernate needs to create objects for you, using Java Reflection. The constructor can be private. However, package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.

## 2.3. The mapping file

The hbm.xml mapping file for this tutorial is the classpath resource `org/hibernate/tutorial/hbm/Event.hbm.xml` as we saw in Section 2.1, “The Hibernate configuration file”

Hibernate uses the mapping metadata to find out how to load and store objects of the persistent class. The Hibernate mapping file is one choice for providing Hibernate with this metadata.

Example 2.1. The `class` mapping element

    <class name="Event" table="EVENTS">

        ...

    </class>

Functions of the `class` mapping element

1. The `name` attribute (combined here with the `package` attribute from the containing `hibernate-mapping` element) names the FQN of the class you want to define as an entity.

2. The `table` attribute names the database table which contains the data for this entity.

Instances of the `Event` class are now mapped to rows in the EVENTS table.

Example 2.2. The `id` mapping element

    <id name="id" column="EVENT_ID">

        ...

    </id>

Hibernate uses the property named by the `id` element to uniquely identify rows in the table.

## Important

It is not strictly necessary for the `id` element to map to the table's actual primary key column(s), but it is the normal convention. Tables mapped in Hibernate do not even need to define primary keys. However, the Hibernate team strongly recommends that all schemas define proper referential integrity. Therefore `id` and primary key are used interchangeably throughout Hibernate documentation.

The `id` element here identifies the EVENT_ID column as the primary key of the EVENTS table. It also identifies the `id` property of the `Event` class as the property containing the identifier value.

The `generator` element nested inside the `id` element informs Hibernate about which strategy is used to generated primary key values for this entity. In this example a simple incrementing count is used.

Example 2.3. The `property` mapping element

    <property name="date" type="timestamp" column="EVENT_DATE"/>

    <property name="title"/>

The two `property` elements declare the remaining two properties of the `Event` class: `date` and`title`. The `date` property mapping includes the `column` attribute, but the `title` does not. In the absence of a `column` attribute, Hibernate uses the property name as the column name. This is appropriate for `title`, but since `date` is a reserved keyword in most databases, you need to specify a non-reserved word for the column name.

The `title` mapping also lacks a `type` attribute. The types declared and used in the mapping files are neither Java data types nor SQL database types. Instead, they are Hibernate mapping types. Hibernate mapping types are converters which translate between Java and SQL data types. Hibernate attempts to determine the correct conversion and mapping type autonomously if the `type` attribute is not present in the mapping, by using Java reflection to determine the Java type of the declared property and using a default mapping type for that Java type.

In some cases this automatic detection might not chose the default you expect or need, as seen with the `date` property. Hibernate cannot know if the property, which is of type `java.util.Date`, should map to a SQL DATE, TIME, or TIMESTAMP datatype. Full date and time information is preserved by mapping the property to a `timestamp` converter (which identifies an instance of the class `org.hibernate.type.TimestampType`).

## Tip

Hibernate makes this mapping type determination using reflection when the mapping files are processed. This process can take time and resources. If startup performance is important, consider explicitly defining the type to use.

## 2.4. Example code

The `org.hibernate.tutorial.hbm.NativeApiIllustrationTest` class illustrates using the Hibernate native API.

## Note

The example code in these tutorials is done as JUnit tests mainly for ease of use. However it is nice in that `setUp` and `tearDown` roughly illustrate how a `org.hibernate.SessionFactory` would be created at the start up of an application and closed at the end of the application lifecycle.

Example 2.4. Obtaining the `org.hibernate.SessionFactory`

    protected void setUp() throws Exception {

        // A SessionFactory is set up once for an application

        sessionFactory = new Configuration()

                .configure() // configures settings from hibernate.cfg.xml

                .buildSessionFactory();

    }

The `org.hibernate.cfg.Configuration` class is the first thing to notice. In this tutorial everything is simply configured via the `hibernate.cfg.xml` file discussed inSection 2.1, “The Hibernate configuration file”.

The `org.hibernate.cfg.Configuration` is then used to create the `org.hibernate.SessionFactory` which is a thread-safe object that is instantiated once to serve the entire application.

The `org.hibernate.SessionFactory` acts as a factory for `org.hibernate.Session` instances as can be seen in the `testBasicUsage` method. A `org.hibernate.Session` should be thought of as a corollary to a "unit of work".

Example 2.5. Saving entities

    Session session = sessionFactory.openSession();

    session.beginTransaction();

    session.save( new Event( "Our very first event!", new Date() ) );

    session.save( new Event( "A follow up event", new Date() ) );

    session.getTransaction().commit();

    session.close();

`testBasicUsage` first creates some new `Event` objects and hands them over to Hibernate for "management" via the `save` method. At that point, Hibernate takes responsibility to perform an `INSERT` on the database.

Example 2.6. Obtaining a list of entities

    session = sessionFactory.openSession();

    session.beginTransaction();

    List result = session.createQuery( "from Event" ).list();

    for ( Event event : (List<Event>) result ) {

        System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() );

    }

    session.getTransaction().commit();

    session.close();

`testBasicUsage` then illustrates use of the Hibernate Query Language (HQL) to load all existing `Event` objects from the database. Hibernate will generate the appropriate `SELECT` SQL, send it to the database and populate `Event` objects with the result set data.

## 2.5. Take it further!

Try the following exercises:

- Reconfigure the examples to connect to your own persistent relational database.

- With help of the Developer Guide, add an association to the `Event` entity to model a message thread.

Copyright © 2004 Red Hat, Inc.

- PrevChapter 1. Obtaining Hibernate
- Top of page
- Front page
- NextChapter 3. Tutorial Using Native Hibernate APIs a...