top of page

Hibernate: Simple Maven Postgres Application in Hibernate using Mapping XML

Hibernate was developed by Gavin King in 2001 as a replacement to use EJB2-style entity beans. Its goal was simple, to provide simple and easy to use persistence capabilities by keeping out of sight complex things and also provide features that were missing from EJB2.

In this series of articles I am going to write about Hibernate. Hibernate is an open source Java persistence framework. Persistence means storing some data to a permanent place and if even the application that created the data is removed, data will be there to use. Basically, Hibernate provides mapping of Object Oriented Model to traditional relational databases.

In this article we will use small database of one table and use that table to map it to Java class through hibernate and then we will do some testing to ensure that data is saved through programming language. There are two ways to map table to Object Oriented World. 1. XML 2. Annotation We will use XML in this article and in next article we will use annotation.

Step 1 . Table Creation

Create a database and create a table called “product”. Define some column of the table which we will use to map to Java Class.

   id integer NOT NULL,
   name character varying(20),
   code character varying(10),
   price numeric(20,10),
   CONSTRAINT pk_product PRIMARY KEY (id)
ALTER TABLE product OWNER TO postgres;

Step 2. Add Dependencies to Maven Project

As this is the Maven Project, so we need to add some dependencies to pom.xml file to make application work.

<project xmlns="" xmlns:xsi=""

Step 3. Create Product Class

Create a file and put it in “src/main/java/com/hibernate/tutorial/” or create package in "src/main/java/" and name it "com.hibernate.tutorial". This class will be used to store data to database later in the tutorial.

package com.hibernate.tutorial;

 * Model class for Product

public class Product implements Serializable {

    private Integer id;
    private String code;
    private String name;
    private BigDecimal price;

    //Define Getter and Setter for variables here.

Step 4. Create Hibernate Mapping file

Create a Product.hbm.xml file and put it in src/main/resources/com/hibernate/tutorial/Product.hbm.xml. Create “resources/com/hibernat/tutorial/” folder if it does not exists. This XML file is used to map Product Class to the product table in database.

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

<hibernate-mapping >
    <class name="com.hibernate.tutorial.Product" table="product" >
        <id name="productId" type="java.lang.Integer">
            <column name="id"/>
            <generator class="identity"/>
        <property name="productCode" type="string">
            <column name="code" length="10" not-null="true"/>
        <property name="productName" type="string">
            <column name="name" length="20" not-null="true"/>
    <property name="productPrice" type="java.math.BigDecimal">
            <column name="price" length="20" not-null="true"/>

Step 5. Postgres Configuration

Create a Hibernate’s configuration file and put under the resources root folder, “src/main/resources/hibernate.cfg.xml“. This is just a configuration to use some particular database. In my case I am using postgres and in the following file shows its configuration.

<?xml version="1.0" encoding="UTF-8"?>

        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/sample_database</property>
        <property name="show_sql">true</property>
        <mapping resource="com/hibernate/tutorial/Product.hbm.xml"></mapping>
</hibernate-configuration >

Step 6. Create HibernatePersistence

Create a class. This will take care of Hibernate start up and retrieve the session. We use this session to store data to database using Product class using save() and commit() method. Create a persistence folder and put this file in it, “src/main/java/com/hibetnate/persistence/” or Package in "src/main/java/" and name it "com.hibernate.persistence"

package com.hibernate.persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePersistence {

private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);

        public static SessionFactory getSessionFactory() {
            return sessionFactory;

        public static void shutdown() {
            // Close caches and connection pools

Step 7. Create Main Class to store values

Now we will use this class to store some data through product class to database using hibernate session.

package com.hibernate.tutorial;

public class Main {

    public static void main( String[] args )
        Session session = HibernatePersistence.getSessionFactory().openSession();

        Product product = new Product();

        //Make some product for storing in database
        product.setPrice(new BigDecimal("18.00"));

        //Save product to database
        Integer productId =(Integer);

        //get data from  database
        product = (Product) session.get(Product.class, productId);

        //close session

508 views0 comments

Recent Posts

See All


Recently I got the chance to work with annotation validators @Pattern on transient field. Basically it was a password field which I had to validate first and then encrypt it and set it in another pers

Get and Load Methods in Hibernate

Both Get and Load methods in hibernate fetch row from databases. The functionality is similar but there is a difference between the way they work. hibernateSession.get() This method will return the re

Many To Many Relationship Using Annotations

This article is about how to write many to many relationships using annotations in hibernate. Many to many means that we can have many rows in one table against many rows in another table. Here is an


bottom of page