Hibernate hello world example

Connect with

Hibernate hello world exampleThis is a Hibernate hello world example with eclipse MySQL for beginners. For simplicity, I kept minimum dependency for the hello world program of Hibernate.

1. Pre Requisite for Hibernate Hello world Example

For your first Hibernate project, we assume that the following things installed in your system (Laptop/desktop). And assuming that you know the basics of Java. This is your first Hibernate program in eclipse as IDE and MySQL as database.
– JDK 5 or later ( any version)
– MySQL 5
– Eclipse (any version)

2. POJO class for Hello world Hibernate Example

This is POJO (Plain Old Java Object) domain model class for the Course entity for your first Hibernate program.

File: Course.java

package com.mysoftkey.hibernate.helloworld;

/**
 * Hibernate Domain model class for course details, for your first Hibernate project.
 * 
 */
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 for First Hibernate Project

Get sessionFactory from the configuration, sessionFactory is a singleton, which means you required only one sessionFactory object and create Session from it. This is the session Hibernate SessionFactory from where we get sessions 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, for first hibernate program in eclipse
 * 
 * @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

This hibernate configuration file, provides the following things, for different activities:
– 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 for hello world Hibernate

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

File: Course.hbm.xml






	
	This class contains the course details.
	
	
		
	
	



6. Run Hibernate CRUD examples

This is main entry point to run this hello world Hibernate CRUD example.

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();*/
  }

// this is create/save method from Hibernate CRUD example  
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) {

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

  /**
   * This method returns all courses from the DB. this is read a part from Hibernate CRUD example
   * 
   * @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 returns the updated course to the database. 
   * Update method from Hibernate CRUD example
   * 
   * @param course
   * @param course name
   */
  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 courses by id. Delete method from Hibernate CRUD example
   * 
   * @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 of Hibernate CRUD (Create, Read, Update and Delete) operations
This is the CRUD ( Create, Read, Update and Delete ) operations of Hibernate example.

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 for first Hibernate Program

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

Thanks for visiting this post for Hello world Hibernate example. You can also visit Java Hibernate ORM Tutorial Listing page for more articles on Hibernate ORM framework.
Happy Learning 🙂 for First Hibernate program example for CRUD (Create, Read, Update and Delete ) opertions.


Connect with

3 thoughts on “Hibernate hello world example”

  1. Pingback: swati

  2. Pingback: rakhi

  3. Pingback: rakhi

Leave a Comment

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