Home Hibernate Hibernate tutorial
12 | 03 | 2010
JBoss 5 AS Book
"JBoss AS 5 development" reviews
Please share your feedback/review with other readers!
Banner
Advertise with Us
Banner
RSS Feed
Login
Sign here for the NewsLetter.



Poll
What book could be in your wish list next XMas ?
 
JBoss admin resources
Banner
JBoss howto

How can you solve deployment errors caused by large war/jar/ear files ?

jboss recipe of the day ...
Read More

How do you configure your .war to be deployed after your EJB ?

jboss recipe of the day ...
Read More

How do I configure a Queue/Topic to work in a cluster?

JBoss recipe of the day ...
Read More
Hibernate tutorial
Written by F.Marchioni   

Hibernate is an object/relational mapping tool for Java environments. What does it mean the term object/relational mapping? simply a technique of mapping a data representation from an object model to a relational data model with a SQL-based schema.
 

For this sample we'll use Hibernate 3.3.1 GA available at www.hibernate.org
The tutorial will be built using Eclipse Enterprise, anyway, since we'll create the Project as simple java project you can easily adapt it on any other IDE.

Ok, at fist let's create a new Java project. We'll name it "Hibernate tutorial".

hibernate tutorial example

Next step is adding a Java class which will be mapped on the DB. We'll create class com.sample.Person :

hibernate tutorial example

Class is a sample JavaBean with properties and getters/setters

package com.sample;

public class Person {
	Long id;
	String name;
	String surname;
	String address;
	
	public Long getId() {
		return id;
	}
	private void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSurname() {
		return surname;
	}
	public void setSurname(String surname) {
		this.surname = surname;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

Create a file named Person.hbm.xml in the same package/folder of your JavaBean Person.


<?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="sample.hibernate.Person" table="Person">

		<id name="id" column="ID">
			<generator class="native" />
		</id>

		<property name="name">
			<column name="NAME" length="16" not-null="true" />
		</property>

		<property name="surname">
			<column name="SURNAME" length="16" not-null="true" />
		</property>

		<property name="address">
			<column name="ADDRESS" length="16" not-null="true" />
		</property>

	</class>
</hibernate-mapping>

The id element is the declaration of the identifier property, name="id" declares the name of the Java property - The column attribute tells Hibernate which column of the PERSON table we use for this primary key.

The nested generator element specifies the identifier generation strategy: in this case we used native, which picks the best strategy depending on the configured database (dialect).

The fields are enlist as "property". Notice the column attribute is added on every property even if this can be skipped if java property = database field.
 

Hibernate configuration file

This file contains the configuration information needed by Hibernate to connect to a RDBMS. For Hibernate's configuration, we can use a simple hibernate.properties file, a slightly more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file.
 

<?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>

    <!-- hibernate dialect -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>

    
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
    <property name="hibernate.connection.username">hibernate</property>
    <property name="hibernate.connection.password">hibernate</property>
    <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    
    <!-- Automatic schema creation (begin) === -->     
    <property name="hibernate.hbm2ddl.auto">create</property>
 
    
    <!-- Simple memory-only cache -->
    <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

     <!-- Enable Hibernate's automatic session context management -->
     <property name="current_session_context_class">thread</property>

    <!-- ############################################ -->
    <!-- # mapping files with external dependencies # -->
    <!-- ############################################ -->


    <mapping resource="com/sample/Person.hbm.xml"/>

</session-factory>
</hibernate-configuration>


As you can see, hibernate.cfg.xml configures the dialect, the JDBC parameters, the connection pool, the cache provider and the single classes mapped.

This example uses MySQL as database. You need to create a database named "hibernatetutorial" and assign to the user "hibernate" all the privileges required.

mysql> create database hibernatetutorial;
Query OK, 1 row affected (0.00 sec)

CREATE USER
'hibernate'@'localhost' IDENTIFIED BY 'hibernate';

mysql> use hibernatetutorial;
Database changed

mysql> grant all privileges on hibernatetutorial to hibernate;
Query OK, 0 rows affected (0.03 sec)

In this configuration file we have set the property "hibernate.hbm2ddl.auto" to true which means automatic drop/creation of the database schema. Remember to comment this line after the first run.

At the bottom we have declared the resource "com/sample/Person.hbm.xml" which is the mapping for Class Person.

The hibernate.cfg.xml file needs to be added to classpath. We recommend creating a new folder for storing the configuration file, for example conf, and add this folder to the CLASSPATH. In Eclipse you have this option in the "Java Build Path" manu, reached from "Properties".

hibernate example tutorial

Project libraries

Ok, now the mapping is complete. Before creating a client appllication we'll add some libraries to the project. The following libraries can be found in Hibernate distribution:
 

  • hibernate3.jar

  • slf4j-api-1.5.2.jar

  • antlr-2.7.6.jar      

  • commons-collections-3.1.jar

  • dom4j-1.6.1.jar

  • javassist-3.4.GA.jar 

  • jta-1.1.jar


Then you need mysql JDBC connector (or the right connector for your RDBMS)

  • mysql-connector-java.jar 

     

Ok. Last library needed is the Simply Logging Facade util. This library allows to plug in the desired logging framework at deployment time (log4j /jdk1.4).

We have tested with the following version:
http://www.slf4j.org/dist/slf4j-1.5.2.zip

You can then choose either log4j or JDK logging implementation: for example if you choose JDK14 logging implementation simply add the following jar:

  • slf4j-jdk14-1.5.2.jar


Accessing your Bean

For completing our Hibernate tutorial we'll create a Java Class “TestPerson” in the package “com.sample”. Add the following source code. It includes methods to create entries in the database, to update and to list them. 


package com.sample;

import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;
 

public class TestPerson {
  
	public static void main(String[] args) {
	 Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
		
	 session.beginTransaction();

         createPerson(session);
         
         queryPerson(session);

        }

	private static void queryPerson(Session session) {
         Query query = session.createQuery("from Person");                 
         List <Person>list = query.list();
         java.util.Iterator<Person> iter = list.iterator();
         while (iter.hasNext()) {
          
          Person person = iter.next();
          System.out.println("Person: \"" + person.getName() +
                          "\", " + person.getSurname() +
                          "\", " + person.getAddress());

         }
        
          session.getTransaction().commit();
		
	}

	public static void createPerson(Session session) {
         Person person = new Person();

         person.setName("Barak");
         person.setSurname("Obhama");       
         person.setAddress("White House");       
        
         session.save(person);
	}
}

As you can see the TestPerson starts at first building a SessionFactory: this object is used to open up new Sessions. A Session represents a single-threaded unit of work, the SessionFactory is a thread-safe global object, instantiated once.

A Session is a single unit of work and begins when it is first needed, that is when the first call to getCurrentSession() is made. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the Session from the thread and closes it for you.







In this example we use a SessionFactoryUtil class to instantiate the SessionFactory just once: 

package com.sample;

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

public class SessionFactoryUtil {

	 private static final SessionFactory sessionFactory;

	    static {
	        try {
	            // Create the SessionFactory from hibernate.cfg.xml
	            sessionFactory = new Configuration().configure().buildSessionFactory();
	        } catch (Throwable ex) {
	            // Make sure you log the exception, as it might be swallowed
	            System.err.println("Initial SessionFactory creation failed." + ex);
	            throw new ExceptionInInitializerError(ex);
	        }
	    }

	    public static SessionFactory getSessionFactory() {
	        return sessionFactory;
	    }

}

Ok, if you have completed all the steps your project should look like this:

hibernate tutorial example

Hibernate Troubleshooting:

Here are some common runtime errors and their possible solution:

org.hibernate.HibernateException: No CurrentSessionContext configured

You haven't configured the current_session_context_class property. Add this to your hibernate.cfg.xml:
 <property name="current_session_context_class">thread</property>


org.hibernate.MappingException: Unknown entity: sample.hibernate.Person

It's likely that you have not added (or added with wrong Classname/namespace) the Class Mapping file.


Could not parse mapping document from resource sample/hibernate/Person.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError

Maybe you have forgot to add the DTD information at the top of your Person.hbm.xml


Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

You are missing the Simply Logging Facade util. Download it http://www.slf4j.org/dist/slf4j-1.5.2.zip and then add either log4j or JDK14 implementation.

Hibernate tutorial code:

Download code for this article
JBoss.org Search
Custom Search
Comments
Search
Only registered users can write comments!

3.26 Copyright (C) 2008 Compojoom.com / Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."