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) {

    public Long getId() {
        return id;

    private void setId(Long 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"
    <class name="hello.Message"

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

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

        <many-to-one name="nextMessage"
                     foreign-key="FK_NEXT_MESSAGE" />


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"

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

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


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 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 through hibernate.cfg.xml. By convention these files are search at the root of the classpath.


Let’s add the dependencies to the pom.xml


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 =  HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();

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


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 {
            Configuration configuration = new Configuration().configure("/hibernate.cfg.xml");
            SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
            SESSION_FACTORY = configuration.buildSessionFactory();
        }catch (Throwable t){
            throw new ExceptionInInitializerError(t);


    public static SessionFactory getSessionFactory(){
        return SESSION_FACTORY;

    public static void shutdown(){

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