Hibernate hello world example

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_example</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">5</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
 
        <property name="hbm2ddl.auto">create</property>
 
         <mapping resource="com/mysoftkey/hibernate/helloworld/Course.hbm.xml"/>
 
    </session-factory>
</hibernate-configuration>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 
<class name="com.mysoftkey.hibernate.helloworld.Course" table="msk_COURSES">
	<meta attribute="class-description">
	This class contains the course details.
	</meta>
	<id name="id" type="long" column="id">
		<generator class="increment"/>
	</id>
	<property name="name" type="string" column="name" not-null="true" />
</class>
 
</hibernate-mapping>

6. Run Hello world Hibernate Application

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

File: CourseMain.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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<Course> 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<Course> 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<Course> listCourse() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    List<Course> 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:

1
2
3
4
5
6
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

1
2
3
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

1
2
3
4
5
6
7
8
9
10
11
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 :)

Please follow and like us:
RSS
Follow by Email
Facebook
LinkedIn
Google+

2 thoughts on “Hibernate hello world example

  1. Pingback: swati
  2. Pingback: rakhi

Leave a Reply

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