Share |
Hibernate Introduction        
Print

Hibernate Introduction

Please read a discussion on ORM, before going further at Introduction To ORM.
Hibernate is an ORM framework. It provides capability to interact with database in an object oriented way. Hibernate provides its own HQL (Hibernate query language) also. The concepts of ORM are now adopted in EJB3.0 in the form of entity beans and Jave Persistence API (JPA). Hibernate supports Entity beans also. This means hibernate can act as an implementation provider for Entity beans. In fact, JBoss uses hibernate as implementation provider for Entity beans. Hibernate has its own set of API's also which at the moment are richer than JPA. Going forward however we might see Entity beans and JPA closing this gap.

Let's make a Java project where we will persist the data into the database. First download the Hibernate Core from download site(external link). Unzip the download at a location and you will find the following important directories/file in it (This might be different from what you see as hibernate keeps on changing the structure).
  • doc - contains the reference document for hibernate
  • eg - example application
  • etc - configuration files
  • grammer
  • lib - contains dependencies for hibernate. See lib/_README.txt for details about libraries.
  • src - source code of hibernate
  • test - test suite
  • hibernate3.jar - hibernate library

Make a simple Java application in your IDE. Have the following libraries in the build path:
From Hibernate Core (<hibernate-distribution-*>/lib/required)
  • antlr-2.7.6
  • commons-collections-3.1.jar
  • dom4j-1.6.1.jar
  • javassist-3.9.0.GA.jar
  • jta-1.1.jar
  • slf4j-api-1.5.8.jar

  • <hibernate-distribution-*>/lib/ -Choose between cglib or javassist
  • <hibernate-distribution>/*hibernate3.jar

Download slf4j from http://www.slf4j.org/dist/(external link)
  • slf4j-simple-1.5.8.jar

  • hsqldb.jar - We will be using hypersonic database for this example. you need to download hypersonic jar. For details see Hypersonic.

Hibernate is a Object relational mapping framework. What it will help us is in saving the objects into the relational world. So let's have our Java class whose object instances at runtime will be saved by hibernate to the database.
public class Student { //Id will correspond the primary key in the database private Long id; protected String name; 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;} }


Now we have the domain class definition with us. Now we will put a mapping file which will map this class to the data model in the database. We are not creating the table in the database as we will use hibernate to generate the data model. Though in real life application you would have your data model already created and placed in the database.
Student.hbm.xml (Put it together with Student class)
<?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 attributes - name - Java class name table - Table to which this class is mapped schema - The schema where it sits id - name - name of property on Java class. It will result in getId() and setId method column - column in table to which it is mapped generator- how the id's to be generated --> <class name="com.oyejava.Student" table="Student" schema="PUBLIC"> <id name="id" column="STUDENT_ID"> <generator class="increment"/> </id> <!-- name - name of property in Java class. getName() and setName() column - column in table to which it is mapped. --> <property name="name" column="NAME" /> </class> </hibernate-mapping>


Now we will provide hibernate the details to connect to the database. Similar to JDBC coding, the connection details and drivers need to be provided to Hibernate. This is done in a XML file.
hibernate.cfg.xml (Put it in the class path)
<?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> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect - This tells the SQL grammer to be used --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Log out all the sql that hibernate is issuing to datbase. This is very useful for debugging --> <property name="show_sql">true</property> <!-- Create the table looking at class and mapping. Very useful in development Use validate in production environments. --> <property name="hbm2ddl.auto">create</property> <!-- Mapping file. --> <mapping resource="com/oyejava/Student.hbm.xml"/> </session-factory> </hibernate-configuration>


Now we will write a utility class which will start the session factory of hibernate, if it is not started and will return the Session factory. This is the most used pattern of boot strapping Hibernate. Session factory contains all the configuration information at runtime. A Session is retrieve from the Session factory. A session is a light weight object which provide services to interact with database. You can think of Session like JDBC connection, thought it may not open the database connection if not required.
HibernateUtil
public class HibernateUtil { private static SessionFactory sessionFactory; static{ try{ //By default it will look for hibernate.cfg.xml in the class path sessionFactory=new Configuration().configure().buildSessionFactory(); }catch(Throwable ex){ throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void shutdown(){ //Close caches and connection pool getSessionFactory().close(); } }

Now let's write the main class in which we will create a Student object and persist it to database
public class HibernateBasic { public static void main(String[] args) { //Get the session from the Session factory Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx= session.beginTransaction(); Student student = new Student(); student.setName("oyeJava"); Long studentId = (Long)session.save(student); System.out.println(studentId); tx.commit(); session.close(); } }

Run the application and check in the database. It should persist a row of data. Download the source code from down below in the attachment section. The libraries has to be included as per the list given above.

In the above example we saw how to configure hibernate using XML mapping. The present trend is however to move towards annotation based mapping. For annotation based mapping see Hibernate Introduction with Annotation

Back to Hibernate Index  Back To Java Home  Back To Home

List of attached files
 id Name   desc uploaded Size Downloads
1 6 zip HibernateBasic.zip View Download   Hibernate Basic Mon 22 of June, 2009 22:42 IST by lalit 4.03 Kb 368

Post new comment

Click for Help
BoldItalicUnderlineStrikethroughExternal LinkSmileys
Anti-Bot verification code: Random Image
Post new comment