Hibernate hello world example

Connect with

hibernate_logoThis is Hibernate hello world program example or you can say this is first program for Hibernate jumpstart program. For simplicity, I keep minimum dependency for hello world program of Hibernate.

1. Pre Requisite

we Asssume that following things installed in you system. And assuming that you know the basic of java.
– JDK 5 or later ( any version)
– mysql 5
– Eclipse (any version)

2. POJO class

This is POJO (Plain Old java Object) domain model class for Course entiry.

File: Course.java

package com.mysoftkey.hibernate.helloworld;

/**
 * This class is a domain model which contains the course details.
 * 
 */
public class Course implements java.io.Serializable {

	private long id;
	private String name;

	public Course() {
	}

	public Course(String courseName) {
		this.name = courseName;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


3. Configure for SessionFactory

Get sessionFactory from the configuration, sessionFactory is a singleton , meaning that , you required only one sessionFactory object and create Session from it. SessionFactory where we get session on every operation.

File: HibernateUtil.java

package com.mysoftkey.hibernate.helloworld;

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

/**
 * This is hibernate utility class for creating SessionFactory object.
 * 
 * @author ranjeet jha
 *
 */
public class HibernateUtil {

  private static final SessionFactory sessionFactory;

  static {
    try {
      // build sessionFactory object and assigned it to private reference 
      sessionFactory = new Configuration().configure().buildSessionFactory();
      // sessionFactory= new AnnotationConfiguration().configure().buildSessionFactory();

    } catch (Throwable ex) {
      ex.printStackTrace();
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
    }
  }

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

4. Hibernate Configuration

In this hibernate configuration file, provides following things:
– JDBC coneection related things,
– hibernate dialect,
– connection url,
– database username,
– database password,
– .hbm mapping entry etc.




    
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/hibernate_example
        root
        root
        5
        org.hibernate.dialect.MySQLDialect
        true

        create

         
         
    


5. Hibernate Mapping file

you required a mapping file in hibernate which does following things:
– map your java POJO class to database table name.
– java property to database column name.
– mapping of primary key generator strategy, here its simple increment but prefereable to use identity.

File: Course.hbm.xml






	
	This class contains the course details.
	
	
		
	
	



6. Run Hello world Hibernate Application

This is main entry point to run this hello world hibernate application.

File: CourseMain.java

package com.mysoftkey.hibernate.helloworld;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class CourseMain {

  public static void main(String[] args) {
    CourseMain obj = new CourseMain();

    Course course = new Course("Computer Science");
    Long cid = obj.saveCourse(course);
    System.out.println("id generated: " + cid);
    List list = obj.listCourse();
    for (Course courseObj : list) {
      System.out.println("course Id: " + courseObj.getId() + " , course name: " + courseObj.getName());
    }
    /* obj.updateCourse(cid, "Mathematics");
     obj.deleteCourse(cid);
     List list2 = obj.listCourse();*/
  }

  public Long saveCourse(Course course) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    Long courseId = null;
    try {
      // begin transaction to start db activity
      transaction = session.beginTransaction();

      // Save course object to database
      courseId = (Long) session.save(course);

      // commit saved object
      transaction.commit();

    } catch (HibernateException e) {

      // roll back if exception occurred.
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
    return courseId;
  }

  /**
   * This method return all course from the db. assuming less no of record added
   * in database
   * 
   * @return
   */
  public List listCourse() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    List courses = null;
    try {
      transaction = session.beginTransaction();
      courses = session.createQuery("from Course").list();
      for (Iterator iterator = courses.iterator(); iterator.hasNext();) {
        Course course = (Course) iterator.next();
        System.out.println(course.getName());
      }
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
    return courses;
  }

  /**
   * This method return update course to database.
   * 
   * @param courseId
   * @param courseName
   */
  public void updateCourse(Long courseId, String courseName) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      Course course = (Course) session.get(Course.class, courseId);
      course.setName(courseName);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  }

  /**
   * This method is used to delete course by id.
   * 
   * @param courseId
   */
  public void deleteCourse(Long courseId) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      Course course = (Course) session.get(Course.class, courseId);
      session.delete(course);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  }

}

Console Output:

Hibernate: select max(id) from msk_COURSES
Hibernate: insert into msk_COURSES (name, id) values (?, ?)
id generated: 1
Hibernate: select course0_.id as id0_, course0_.name as name0_ from msk_COURSES course0_
Computer Science
course Id: 1 , course name: Computer Science

6. MySQL database console

Open command propt, go to MYSQL bin directory and use command mysql -u -p options

C:\Program Files\MySQL\MySQL Server 5.5\bin>mysql -uroot -proot

mysql>

Note: in my case, usename and password both are root.

MySQL Console

mysql> use hibernate_example
Database changed
mysql> select * from msk_courses;
+----+------------------+
| id | name             |
+----+------------------+
|  1 | Computer Science |
+----+------------------+
1 row in set (0.00 sec)

mysql>

7. Reference and Source Code

Your comments are welcome to improve this post. Happy Learning your first program in Hibenate 🙂


Connect with

3 thoughts on “Hibernate hello world example

  1. Pingback: swati
  2. Pingback: rakhi
  3. Pingback: rakhi

Leave a Reply

Your email address will not be published. Required fields are marked *