Sample program using hibernate

Hi Everyone, in this blog post, I will write a sample program using hibernate. Please check my earlier post about hibernate, which is mainly the introduction of hibernate - Introduction to hibernate. In this program, we are trying to add some data to database using hibernate.

Here, we have mainly 2 classes. One for creating the bean class and the second one for creating the SessionFactory and saving the transaction details.

The bean class (AccountDetails.java) which describes the table and rows is as follows:

package com.hibernate;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name = "ACCOUNT")
public class AccountDetails {

    @Id
    public int accountId;
    public String accountName;
    public Date accountDate;
    
    public int getAccountId() {
        return accountId;
    }
    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }
    public String getAccountName() {
        return accountName;
    }
    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }
    public Date getAccountDate() {
        return accountDate;
    }
    public void setAccountDate(Date accountDate) {
        this.accountDate = accountDate;
    }
    
}


The class (SetData.java) to persist the data and creation of hibernate session factory is as follows:

package com.hibernate;

import java.util.Date;

import org.hibernate.cfg.Configuration;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class SetData {
    
    public static void main(String[] args) 
    {
    AccountDetails account1 = new AccountDetails();
    AccountDetails account2 = new AccountDetails();
    
    account1.setAccountId(101);
    account1.setAccountName("Gilchrist");
    account1.setAccountDate(new Date(71,5,16));
    
    account2.setAccountId(102);
    account2.setAccountName("Ponting");
    account2.setAccountDate(new Date(76,8,18));
    
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(account1);
    session.save(account2);
    session.getTransaction().commit();
    }
    
}


The hibernate configuration xml is as follows.

 <?xml version="1.0" encoding="utf-8"?>  
 <!DOCTYPE hibernate-configuration PUBLIC  
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
 <hibernate-configuration>  
  <session-factory>  
  <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>  
  <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost</property>  
  <property name="hibernate.connection.username">sa</property>  
  <property name="hibernate.connection.password"></property>  
  <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>  
  <property name="hibernate.hbm2ddl.auto">create</property>  
  <property name="show_sql">true</property>  
  <mapping class="com.hibernate.AccountDetails"></mapping>  
 </session-factory>  
 </hibernate-configuration>  

Following are some of the important properties which are used in hibernate config file.

  1. hiberntae.connection.driver_class - The jdbc driver for connecting to database.
  2. hibernate.connection.url - The url for connecting to database.
  3. hibernate.connection.username - The username for connecting to database.
  4. hibernate.connection.password - The password for connecting to database.
  5. hibernate.dialect - Allows hibernate to generate SQL optimized for a particular relational database.
  6. hibernate.hbm2ddl.auto - Automatically validates or exports data to database when SessionFactory is created. Different types are create, update, validate, create-drop. 
  7. show_sql - By putting show_sql = "true", all SQL statements will be written to console. If we dont want to write the SQL statements to console, give show_sql = "false".
There are many other commands, but currently we are dealing with only these 7. The rest will be covered in  during the upcoming posts about hibernate.


In this example, I have used HSQL as the relational database. Please refer my blogpost on HSQLDB to learn more about HSQLDB. The database creation class (Database.java) is as follows:

package com.hibernate.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Database {
    public static void main(String[] args) {
        try
        {
            String connectionURL ="jdbc:hsqldb:hsql://localhost";
            Class.forName("org.hsqldb.jdbcDriver");
            
            Connection con = DriverManager.getConnection(connectionURL,"sa","");
            Statement stmt = con.createStatement();
            
            ResultSet rs = stmt.executeQuery(" select * from ACCOUNT");
        while(rs.next())
        {
            System.out.println("ID = "+rs.getString(1));
            System.out.println("Date = "+rs.getString(2));
            System.out.println("Name = "+rs.getString(3));
            System.out.println();
        }
        }
        catch(Exception e )
        {
            e.printStackTrace();
        }
        
        
    }
}



The output which we get after running the program SetData.java is as written below. Here using hibernate 2 rows of data are inserted to database.

Hibernate: insert into ACCOUNT (accountDate, accountName, accountId) values (?, ?, ?)
Hibernate: insert into ACCOUNT (accountDate, accountName, accountId) values (?, ?, ?)


To verify whether data is stored in database, we are checking its contents. The contents are as follows:

ID = 101
Date = 1971-06-16 00:00:00.000000000
Name = Gilchrist

ID = 102
Date = 1976-09-18 00:00:00.000000000
Name = Ponting


I hope everyone understood this post about writing a sample program in hibernate. Check my upcoming posts to read more about hibernate. Please comment below if you have any doubts or suggestions. Every comment will be responded soon.

Thank you for reading the post.

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++