How to configure Hibernate in Eclipse



Hibernate

This post tells you how to confugure Hibernate in Eclipse or RAD or other IDEs.
Hibernate is an Object/Relational persistence and query service.Hibernate helps you to map database tables to a Java class. Hibernate gives you its own query language, HQL which helps you to write your application with less SQL knowledge.
Yes, Hibernate is an open source api and you can freely download it and use.

hibernate.cfg.xml

Most important step in Hibernate setup is the configuration part. You have to configure everything priorly. The database url, username, password, mapping information and so on. There are two ways to do this.
1. using hibernate.properties file
2. hibernate.cfg.xml
Some of the configurations take its default value if you leave them unconfigured. Some configurations are mandatory.
You have to place this file in the classpath of your application or in the applications root directory.

Some important configurations

hibernate.connection.driver_class - This tells which driver class to use to connect the database server.
hibernate.connection.url - Your database URL
hibernate.connection.username - Your database user name
hibernate.connection.password - Your database password
hibernate.connection.pool_size - This tells the number of connections in the database connection pool
hibernate.dialect - This tells what database you are using in your application. For example MySql,Oracle,HSQLDB
hibernate.connection.autocommit - This tells whether to use auto-commit or not.
hibernate.connection.datasource -If you configure your database url,username,password and other cnfigurations in an application server datasource, use this property to connect to the atasource
hibernate.jndi.class - This is the initial context class for the JNDI

Some driver classes

Note: The driver class names may be different in different driver versions.


Database          
Driver
MySql  
com.mysql.jdbc.Driver
HSQLDB  
org.hsqldb.jdbc.JDBCDriver
Oracle  
oracle.jdbc.OracleDriver
DB2   
com.ibm.db2.jcc.DB2Driver
PostgreSQL
org.postgresql.Driver
Sybase  
net.sourceforge.jtds.jdbc.Driver


Some hibernate dialects



Database
Dialect Property
MySQL
org.hibernate.dialect.MySQLDialect
Oracle (any version)
org.hibernate.dialect.OracleDialect
Oracle 11g
org.hibernate.dialect.Oracle10gDialect
Oracle 10g
org.hibernate.dialect.Oracle10gDialect
Oracle 9i
org.hibernate.dialect.Oracle9iDialect
DB2
org.hibernate.dialect.DB2Dialect
HSQLDB
org.hibernate.dialect.HSQLDialect
HypersonicSQL
org.hibernate.dialect.HSQLDialect
Informix
org.hibernate.dialect.InformixDialect
Interbase
org.hibernate.dialect.InterbaseDialect
MS SQL Server 2005
org.hibernate.dialect.SQLServer2005Dialect
MS SQL Server 2008
org.hibernate.dialect.SQLServer2008Dialect
PostgreSQL
org.hibernate.dialect.PostgreSQLDialect
Sybase
org.hibernate.dialect.SybaseDialect

Hibernate mapping

There are two ways to map your database table with the Java class.
1. XML configuration
2. Annotation

In my example I have used annotation based approach.
javax.persistence api gives you the annotaions to create the mapping.
A mapping class is a plain java class with getters and setters for its properties.

Some basic and important annotaions

@Entity: Specifies that the class is an entity
@Table: Tells this class is mapped to which database table
@Id: Tells the primary key of the database column
@Column: Used to define the database columns

Lets go to the sample application:
Application structure is given below


My sample application is a very simple java application which uses HSQLDB as the backend database and hibernate to access,store values to the database.
The database has one table called PERSONS.
The table structure is:

PERSONS
--------------------------------------------
P_ID    Int Primary key
FIRSTNAME    Varchar(2)
LASTNAME    Varchar(2)
ADDRESS          Varchar(2)
CITY     Varchar(2)

The java mapping class has properties for all these columns. 
Note: It is not necessary to have properties for all the columns. You should have property for the primary key column and other columns are optional.

package com.sample.hibernate.dto;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "PERSONS", schema = "PUBLIC")
public class Persons {
 private int pid;
 private String firstName;
 private String lastName;
 private String address;
 private String city;

 /**
  * @return the pid
  */
 @Id
 @Column(name = "P_ID", unique = true, nullable = false)
 public int getPid() {
  return pid;
 }

 /**
  * @param pid
  *            the pid to set
  */
 public void setPid(int pid) {
  this.pid = pid;
 }

 /**
  * @return the firstName
  */
 @Column(name = "FIRSTNAME")
 public String getFirstName() {
  return firstName;
 }

 /**
  * @param firstName
  *            the firstName to set
  */
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 /**
  * @return the lastName
  */
 @Column(name = "LASTNAME")
 public String getLastName() {
  return lastName;
 }

 /**
  * @param lastName
  *            the lastName to set
  */
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 /**
  * @return the address
  */
 @Column(name = "ADDRESS")
 public String getAddress() {
  return address;
 }

 /**
  * @param address
  *            the address to set
  */
 public void setAddress(String address) {
  this.address = address;
 }

 /**
  * @return the city
  */
 @Column(name = "CITY")
 public String getCity() {
  return city;
 }

 /**
  * @param city
  *            the city to set
  */
 public void setCity(String city) {
  this.city = city;
 }

 @Override
 public String toString() {
  return String.format(
    "id=%d\nFirst name=%s\nLast name=%s\nAddress=%s\nCity=%s",
    this.pid, this.firstName, this.lastName, this.address,
    this.city);
 }

}


My hibernate.cfg.xml is given below
Here
hibernate.connection.driver_class is org.hsqldb.jdbc.JDBCDriver
hibernate.connection.url is jdbc:hsqldb:hsql://localhost/
hibernate.connection.username is SA
hibernate.connection.password is '' -(No password)
hibernate.connection.pool_size is 1
hibernate.dialect class is org.hibernate.dialect.HSQLDialect

Below property defines what is your mapping class. You can map any number of classes here;
<mapping class="com.sample.hibernate.dto.Persons"/>
Otherwise you can give the mappings in some other xml and give the mapping resource name in this configuration file using
<mapping resource="mymapping.xml">

<?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 name=""> -->
<session-factory>
  <property name="hibernate.connection.driver_class">org.hsqldb.jdbc.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.connection.pool_size">1</property>
  <property name="show_sql">true</property> 
  <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
  
  <!-- property name="mappingDirectoryLocations">classpath:WEB-INF/classes/hibernate</property-->
  
   <!-- Mapping classes -->
   <mapping class="com.sample.hibernate.dto.Persons"/>
   
</session-factory>
</hibernate-configuration>

I have created a DAO class to do the insert,update,select operations on the database table.

/**
 * 
 */
package com.sample.hibernate.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

import com.sample.hibernate.dto.Persons;

/**
 * @author Vienna
 * 
 */

public class PersonsDAO {
 private static SessionFactory factory;

 public PersonsDAO() {
  getSession();
 }

 public void getSession() {
  try {
   factory = new AnnotationConfiguration().configure()
     .buildSessionFactory();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }

 public Persons get(int id) {
  Session session = factory.openSession();
  Transaction tx = null;
  Persons persons = null;
  try {
   tx = session.beginTransaction();
   persons = (Persons) session.get(Persons.class, id);
  } catch (HibernateException e) {
   if (tx != null)
    tx.rollback();
   e.printStackTrace();
  } finally {
   session.close();
  }
  return persons;
 }

 public void update(Persons persons) {
  Session session = factory.openSession();
  Transaction tx = null;
  try {
   tx = session.beginTransaction();
   session.update(persons);
   tx.commit();
  } catch (HibernateException e) {
   if (tx != null)
    tx.rollback();
   e.printStackTrace();
  } finally {
   session.close();
  }
 }

 public void insert(Persons persons) {
  Session session = factory.openSession();
  Transaction tx = null;
  try {
   tx = session.beginTransaction();
   session.save(persons);
   tx.commit();
  } catch (HibernateException e) {
   if (tx != null)
    tx.rollback();
   e.printStackTrace();
  } finally {
   session.close();
  }
 }
}


And a simple driver class to run this application. This class will insert,update,retrieve values from the database and display the result in the console.

/**
 * 
 */
package com.sample.hibernate.driver;

import com.sample.hibernate.dao.PersonsDAO;
import com.sample.hibernate.dto.Persons;

/**
 * @author Vienna
 *
 */
public class HibernateRunner {
 public static void main(String args[]){
  PersonsDAO personsDAO=new PersonsDAO();
  //Insert new record
  Persons persons3=new Persons();
  persons3.setPid(3);
  persons3.setFirstName("name");
  persons3.setLastName("last");
  persons3.setAddress("add");
  persons3.setCity("cc");
  personsDAO.insert(persons3);
  //Get existing record
  Persons persons=personsDAO.get(1);
  if(null!=persons){
   System.out.println(persons.toString());
  }else{
   System.out.println("No records found");
  }
  //Update existing record
  Persons persons2=new Persons();
  persons2.setPid(3);
  persons2.setFirstName("name");
  personsDAO.update(persons2);
 }
}

Run this application, and you will see below log in your console;
This application inserts one entry to the database table and prints the values. Then it updates the entry with different values and prints the values again.


You can see the data inserted in the HSQLDB manager console;


Here is the source code of this sample application;
HibernateSample.zip




Reactions:

0 comments :

Post a Comment