Today, We’ll create a simple Hibernate project with a single persistent class Message using Maven through XML configuration and mapping. We’ll be using H2 database. Hibernate is the most popular ORM tool which is quite rich in features. It promotes the usage of POJO’s for relational mapping. So, our Message will be a simple POJO like:

public class Message {

    private Long id;
    private String text;
    private Message nextMessage;

    public Message() {
    }

    public Message(String text) {
        this.setText(text);
    }

    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Message getNextMessage() {
        return nextMessage;
    }

    public void setNextMessage(Message nextMessage) {
        this.nextMessage = nextMessage;
    }
}

As you can see, Message domain has three properties, one is Id which is going to represent the primary key of the table, then a text and we have also added a relation that refers to the record in the same table. In Hibernate, there’s a convention of keeping one mapping file per domain. Mappings are written in simple readable XML. Let’s add one for the Message domain.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="hello.Message"
           table="MESSAGES">

        <id name="id" column="MESSAGE_ID">
            <generator class="increment"/>
        </id>

        <property name="text" column="MESSAGE_TEXT"/>

        <many-to-one name="nextMessage"
                     cascade="all"
                     column="NEXT_MESSAGE_ID"
                     foreign-key="FK_NEXT_MESSAGE" />

</class>
</hibernate-mapping>

Save this as message.hbm.xml. Next, add the configuration file for the hibernate to create the Hibernate Session which will be used to interact with the database in the application.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
        <hibernate-configuration>
    <session-factory>

        <!--Logging configuration-->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!--Mapping files-->
        <mapping resource="hello/Message.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

Save this file as hibernate.cfg.xml. By convention this name is searched in the classpath. And finally, add the properties file for the hibernate hibernate.properties. This is optional as it is the first file that is used to load the configuration for the Hibernate and you can overridden the properties provided in hibernate.properties through hibernate.cfg.xml. By convention these files are search at the root of the classpath.

hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:file:./db/helloWorldDB;AUTO_SERVER=TRUE
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect

Let’s add the dependencies to the pom.xml

<dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.7.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>4.2.7.Final</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.3.164</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

As you can see, we are using H2 database in our application. Now, it’s time to put all the code into action. Let’s add a Main class where we’ll create the hibernate Session for using Hibernate ORM to interact with the database.

public class HelloWorld {
        private static final Logger log = Logger.getLogger(HelloWorld.class);
    public static void main(String... args){
        /* first unit of db work */
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();

        Message message = new Message();
        message.setText("Hello world!");
        session.save(message);
        tx.commit();
        session.close();

        log.info("=======================================================");
        session =  HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();

        message = new Message();
        message.setText("Second message!");
        message.setNextMessage(new Message("Nested message!"));

        session.save(message);
        tx.commit();
        session.close();

    }
}

In case you are wondering about the HibernateUtil class. It’s the utility class that we have used for abstracting the details for creating the Hibernate session.

public class HibernateUtil {
    private static final SessionFactory SESSION_FACTORY;

    static {
        try{
            Configuration configuration = new Configuration().configure("/hibernate.cfg.xml");
            SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
            schemaUpdate.execute(true,true);
            SESSION_FACTORY = configuration.buildSessionFactory();
        }catch (Throwable t){
            throw new ExceptionInInitializerError(t);
        }

    }

    public static SessionFactory getSessionFactory(){
        return SESSION_FACTORY;
    }

    public static void shutdown(){
        SESSION_FACTORY.close();
    }
}

Run the HelloWorld and use H2 db browser to check out the records created.