top of page
index-1-1.jpg

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.

CREATE TABLE product
(
   id integer NOT NULL,
   name character varying(20),
   code character varying(10),
   price numeric(20,10),
   CONSTRAINT pk_product PRIMARY KEY (id)
)
WITH (
  OIDS = FALSE
)
;
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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hibernate.tutorial</groupId>
  <artifactId>SimpleApp</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SimpleApp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.2.3.Final</version>
    </dependency>
    <dependency>
	<groupId>postgresql</groupId>
	<artifactId>postgresql</artifactId>
	<version>9.1-901.jdbc4</version>
    </dependency>
  </dependencies>
</project>

Step 3. Create Product Class

Create a Product.java file and put it in “src/main/java/com/hibernate/tutorial/Product.java” 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"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

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

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"?>

<hibernate-configuration>
    <session-factory>
        <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>
    </session-factory>
</hibernate-configuration >

Step 6. Create HibernatePersistence

Create a HibernatePersistence.java 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/HibernatePersistence.java” 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
            getSessionFactory().close();
        }
        }

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();

        session.beginTransaction();
        Product product = new Product();

        //Make some product for storing in database
        product.setId(1);
        product.setName("COKE");
        product.setCode("C001");
        product.setPrice(new BigDecimal("18.00"));

        //Save product to database
        Integer productId =(Integer) session.save(product);
        session.getTransaction().commit();

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

        //close session
        HibernatePersistence.shutdown();
}
}


513 views0 comments

Recent Posts

See All

Comments


bottom of page