RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Simplify Java Object Persistence with Hibernate : Page 2

The 'impedance mismatch' between relational databases' tabular orientation and object-oriented Java's hierarchical one is a perennial problem for which the Java world has several good solution offerings. The second in a three-part series, this article examines the ways that the Hibernate framework attempts to simplify the chore of connecting relational databases and the Java programming language.

The Hibernate Configuration File
You can configure the Hibernate environment in a couple of ways. One standard way that proves very flexible and convenient is to store the configuration in a file named hibernate.cfg.xml. You place the configuration file at the root of a Web application's context classpath (e.g. WEB-INF/classes). You then access the file and read it using the net.sf.hibernate.cfg.Configuration class at runtime.

The hibernate.cfg.xml file defines information about the database connection, the transaction factory class, resource mappings, etc. The following code demonstrates a typical configuration file:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
   "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
      <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
      <property name="connection.url">jdbc:hsqldb:data/userejb</property>
      <property name="connection.username">sa</property>
      <property name="connection.password"></property>
      <property name="show_sql">true</property>
      <property name="dialect">net.sf.hibernate.dialect.HSQLDialect</property>
      <property name="transaction.factory_class">
      <mapping resource="com/jeffhanson/businesstier/model/UserInfo.hbm.xml"/>
The Hibernate Mapping Configuration File
Hibernate applications make use of mapping files containing metadata defining object/relational mappings for Java classes. A mapping file is designated with a suffix of .hbm.xml. Within each configuration file, classes to be made persistent are mapped to database tables and properties are defined which map class-fields to columns and primary keys. The following code illustrates a typical Hibernate configuration file named UserInfo.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC


    <class name="com.jeffhanson.businesstier.model.UserInfo" table="USER">

        <id name="id" type="string" unsaved-value="null" >
            <column name="USER_ID" not-null="true"/>
            <generator class="uuid.hex"/>

        <property name="fullName">
            <column name="FULLNAME" length="32" not-null="true"/>
        <property name="address"/>
        <property name="city"/>
        <property name="state"/>
        <property name="zip"/>



Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date