Tuesday, September 9, 2014

Hibernate Getting Started From Scratch In 3 Simple Steps

This is the quick starter guide to get started with hibernate  framework with Java in 3 simple steps using Eclipse IDE. The guide explains the steps required right from scratch in Windows platform. In short the hibernate framework is based on Java and Object Relation Mapping(ORM) tool which significantly reduces the work otherwise while dealing with relational databases using programming languages. It is assumed that the reader knows MySql and Java Programming Language basics, if not its recommended to learn them first. Please refer to the post for getting started with MySQL and JAVA.

1. Hibernate Installation

Download hibernate files from http://sourceforge.net/projects/hibernate/files/ the latest version at present is 4.x. You'll get zipped file called "hibernate-release-4.3.1.Final", unzip this into your local hard drive. Under the unzipped folder, there is lib\required folder which is the core of hibernate framework.

2. Create a Simple Java Project in Eclipse

You've created a database and Employee table in MySQL in the previous post. If not you need do that first. Add all the required hibernate jar files that you downloaded in the step1 to eclipse project build path.

2.1 Create a class called "Employee.java" which is a model class that is going to be mapped to Employee database table as shown below.



import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee")

public class Employee implements Serializable{
       private static final long serialVersionUID = 1L;
       @Id
       @GeneratedValue
       @Column (name="empid")
       private int empId;
      
       @Column(name="firstname")
       private String firstName;
      
       @Column (name="lastname")
       private String lastName;
      
       @Column (name="cubicle")
       private String cubile;

       public int getEmpId() {
              return empId;
       }
       public void setEmpId(int empId) {
              this.empId = empId;
       }
       public String getFirstName() {
              return firstName;
       }
       public void setFirstName(String firstName) {
              this.firstName = firstName;
       }
       public String getLastName() {
              return lastName;
       }
       public void setLastName(String lastName) {
              this.lastName = lastName;
       }
       public String getCubile() {
              return cubile;
       }
       public void setCubile(String cubile) {
              this.cubile = cubile;
       }
}


2.2 Create hibernate configuration file called hibernate.cfg.xml in source folder of your eclipse project with contents as shown below. This config file has information about connectivity driver, url, db credentials etc and importantly mappings from Java class to MySQL database table.


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mydatabase</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">your_password</property>
<property name="hibernate.connection.pool_size">10</property>

    <property name="show_sql">true</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.current_session_context_class">thread</property>
   
    <mapping class="Employee"/>
   
    </session-factory>

</hibernate-configuration>

2.3 Create a utility class that creates hibernate session factory as shown below.


import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
       private static final SessionFactory sessionFactory;
       static{
              try{
                     Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
                     StandardServiceRegistryBuilder sb= new StandardServiceRegistryBuilder();
                     sb.applySettings(cfg.getProperties());
                     StandardServiceRegistry standardServiceRegistry = sb.build();
                     sessionFactory = cfg.buildSessionFactory(standardServiceRegistry);
              }catch(Throwable th){
                     System.out.println("Session factory creation failed...");
                     throw new ExceptionInInitializerError(th);
              }
       }

       public static SessionFactory getSessionFactory(){
              return sessionFactory;
       }
}

2.4 Now create HelloWorld Java program as shown below that uses the hibernate session factory, begins the transaction and displays contents from "Employee" table.

import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class HibernateHelloWorld {
       public static void main(String[] args) throws Exception{
              SessionFactory sessionFactory  = HibernateUtil.getSessionFactory();
              Session session = sessionFactory.getCurrentSession();
              org.hibernate.Transaction tr= session.beginTransaction();
              Query query = session.createQuery("from Employee");
              List list = query.list();
              for(Iterator i=list.iterator();i.hasNext();){
                     Employee employee = (Employee)i.next();
                     System.out.println("Employee name=="+ employee.getFirstName());
              }
              tr.commit();
              sessionFactory.close();
       }
}

3. Run HelloWorld Java program as Java Application and see the console for the result as shown below.

INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Sep 9, 2014 8:51:28 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select employee0_.empid as empid1_0_, employee0_.cubicle as cubicle2_0_, employee0_.firstname as firstnam3_0_, employee0_.lastname as lastname4_0_ from employee employee0_
Employee name==John

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...