First Hibernate Tutorial –Get Hands on Experience -Part I
Hibernate is a powerful, high performance object/relational persistence and query service. It maps database tables to objects so that the database tables can be queried and used as objects.
This hibernate tutorial gives a step by step solution to develop a first Hibernate application using Eclipse.
- Requirements:Eclipse 3, Mysql Database, JDK 1.5, Download hibernate from https://www.hibernate.org/30.html and unzip it.
- Setting Up Project :
Step 1: Create project.Open Project Wizard and create simple java project
Next Screen -> New Java Project Screen appears. Enter Project Name.
Now you can see the project being setup and listed in the package explorer(left)
Step 2: Add jars to the path Create a user Library
Right click project and select Properties
Select Libraries
Click Add Library -> User Library
Click Next
Click userlibraries
Click New Button to create new userlibrary
You can see HibernateLib library created
Open the downloaded and unzipped Hibernate directory and Add jars from downloaded Hibernate 3/lib and hibernate3.jar to HibernateLibrary.
Select TraningProject /lib directory and select all the jars –> open
Select all jars and click open. You can see jars being selectd as below:
Click ok –> Finish –> Ok. Now you can see the jars are being added to referenced libraries section in package explorer.
Also download mysql-connector.jar and include in your library.
Configuring Hibernate
Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.Create a file named hibernate.cfg.xml in src directory. Right click –> new –> file
Copy following contents and save.
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>
<hibernate-configuration>
<session-factory>
<property>com.mysql.jdbc.Driver</property>
<property>jdbc:mysql://localhost/HibernateTest</property>
<property>root</property>
<property>yourPassword</property>
<property>10</property>
<property>true</property>
<property>org.hibernate.dialect.MySQLDialect</property>
<property>update</property>
<!– Mapping files –>
<mapping resource=”contact.hbm.xml”/>
</session-factory>
</hibernate-configuration>
In the above configuration file we specified to use the ” HibernateTest ” (Replace with your Database name on mysql ) which is running on localhost and the user of the database is root with password yourPassword (Replace with your mysql db password). The dialect property is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database. The <mapping resource=”contact.hbm.xml”/> property is the mapping for our contact table.
Mysql Setup:
Login to mysql command line interface.
Create new Database:
mysql> create database HibernateTest;
mysql> connect HibernateTest;
mysql> Create table CONTACT(
ID int(15),
FIRSTNAME varchar(50) ,
LASTNAME varchar(50),
EMAIL varchar(150));
Commit your changes:
mysql> commit;
Creating Persisting Class.
This class will be used to map to Contact Table:
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id; public String getEmail() {
return email;
} public String getFirstName() {
return firstName;
} public String getLastName() {
return lastName;
} public void setEmail(String string) {
email = string;
} public void setFirstName(String string) {
firstName = string;
} public void setLastName(String string) {
lastName = string;
} public long getId() {
return id;
} public void setId(long l) {
id = l;
}}
Mapping the Contact Object to the Database Contact table
The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. Create a file named contact.hbm.xml.Here is the code for contact.hbm.xml:
<?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=”Contact” table=”CONTACT”>
<id name=”id” type=”long” column=”ID” >
<generator/>
</id>
<property name=”firstName”>
<column name=”FIRSTNAME” />
</property>
<property name=”lastName”>
<column name=”LASTNAME”/>
</property>
<property name=”email”>
<column name=”EMAIL”/>
</property>
</class>
</hibernate-mapping>
Developing Code to Test Hibernate
Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file. Then the save method on session object is used to save the contact information to the database:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class MyExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println(“Inserting Record”);
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName(“Smitha”);
contact.setLastName(“Rao”);
contact.setEmail(“smithaxxx@yahoo.com“);
session.save(contact);
System.out.println(“Done”);
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
Run the Hibernate project:
right click on the MyExample.java file –> run –> java application.
You should see something following:
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)
Hope this tutorials helps. In Next tutorial I’ll explain how you can use annotations instead of using mapping file like Contact.hbm.xml.
I am hoping this Hibernate Tutorial would have been helpful to you. Do put in your feedback and comments.
Check Part II of this tutorial to get more clarity on how the code worked


Great headline. If your cookie has a bite-sized action and your reader completes the action, I think two things happen. Their self-confidence goes up (which feels good) and their trust in you increases.
Nice but i think something is missing.
awesome tutorials as per me. really very helpfull for the begginer with hibernate.
thanks a lot.
best wishes to all.
@hoodia gordonii
Hoodia , can you help in pointing out what is missing so that we can update accordingly ?
@Virendra
Thanks Virendra. I am glad you liked it.
There is no “name” attribute in any “property” element in hibernate.cfg.xml
@Goran,
For db settings, you have to replace db name by your local db name.
For example:
You have to replace the jdbc:mysql://localhost/HibernateTest string in the hibernate.cfg.xml file with your local machine’s db settings where localhost : machine name (you can append port number infront of it like: localhost:3306 if port number is other than 3306)
HibernateTest: replace this by your database name.
Great stuff to get going , Thanks !
Good stuff , but needed to change contact.hbm.xml , as well as needed to put transaction begin and commit to save data, flush did not work for me.
Transaction had not been put here because they are managed in service layer through Spring. Sorry about that.
I’ve a problem with this sample.
The eclipse editor doesn’t like the hibernate.cfg.xml.
It sais the element should be in the following format:
yyy
@Vinay
Hi,
flush doesn’t work for me too. How do I specify transaction begin and end ?? (I have no Spring either)
thanks.
Hi,
well, using session.beginTransaction() and then transaction.commit() works. Is that the way you do it, or is there any other way for beginners ?
thanks again.
@sbt yes session.beginTransaction() and transaction.commit will work.
In real world application , we will either use Spring or EJB to manage transaction.
In small application , there is no harm in manually controlling transaction as you are doing it.
Thanks for the tutorial, it’s one of the best I found to have something working with Hibernate very quickly!
If you have problem with xml files, it’s probably quote that were messed up when doing copy/past. I actually use another template for the xml to avoid having to replace every quote. Also as some people say, you need to add transaction begin and commit for this example to work.
For the transaction to work use:
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
session = sessionFactory.openSession();
Transaction tran = session.beginTransaction();
tran.begin();
// Create new instance of Contact and set values in it by reading
// them from form object
System.out.println(“Inserting Record”);
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName(“Smitha”);
contact.setLastName(“Rao”);
contact.setEmail(“smithaxxx@yahoo.com”);
session.save(contact);
tran.commit();
System.out.println(“Done”);
@remy2France I am glad you liked it. Thanks for adding the code for transactions. I am sure others would benefit from it.
Thanks to the various comments I was able to make the example work. I also had issues with the comment statements in the XML files. They caused parsing problems and I had to remove them. Other than that it was relatively smooth sailing.
Very easy and well formed tutorial. I had some issues with quotes thing because of copy paste but overall best tutorials for beginners.
Nice tutorial, thank you for this and also the comments from other, they were helpful too.
I found a few typos as mentioned above and things I needed to be aware of because I put my hbm and java files in separate packages. The listings of the tutorial files that I got working is shown below (this is for MySQL), perhaps it can help other people too.
Regards
Robert.
Cfg:
com.mysql.jdbc.Driver
jdbc:mysql://localhost/HibernateTest
root
sa
10
true
org.hibernate.dialect.MySQLDialect
org.hibernate.transaction.JDBCTransactionFactory
thread
<!– update
–>
hbm:
Contact:
package com.hibernateTest.dom;
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
public long getId() {
return id;
}
public void setId(long l) {
id = l;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String string) {
firstName = string;
}
public String getLastName() {
return lastName;
}
public void setLastName(String string) {
lastName = string;
}
public String getEmail() {
return email;
}
public void setEmail(String string) {
email = string;
}
}
MyExample:
package com.hibernateTest.main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hibernateTest.dom.Contact;
public class MyExample {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(MyExample.class);
Transaction tx = null;
Session session = null;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
tx = session.beginTransaction();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println(“Inserting Record”);
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName(“Smitha”);
contact.setLastName(“Rao”);
contact.setEmail(“smithaxxx@yahoo.com”);
session.save(contact);
tx.commit();
System.out.println(“Done”);
}catch(Exception e){
tx.rollback();
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
@robbie70 Thanks for your code input. I am sure other readers will benefit from your contribution.
Very good tutorial !
However, please mention that simple cut paste will break the xml parsing due to the quote issue. By the way, if time permit, please update the lib including list as new hibernate lib is quite different now.
Thanks,
I’ve got a null pointer on : session.flush();
So I guess my config is wrong, does anyone what’s wrong?
com.mysql.jdbc.Driver
jdbc:mysql://localhost/DB_NAME
root
pass
10
true
org.hibernate.dialect.MySQLDialect
update
Good tutorial, at first it did not work for me, but when I added the transaction.begin and commit it worked like a well oiled machine.Thanks again, can’t wait for your next tutorial.
Thank yo Mr wizard. I am glad it helped you and you liked it. We have some other very goo tutorials around JPA and Spring. If you are looking for anything specific ,do let us know.
While running the above example in eclipse, i’m getting the following error
_——————————————————————————————
Exception in thread “main” java.lang.ExceptionInInitializerError
at MyExample.main(MyExample.java:10)
Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException) (Caused by org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException))
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:543)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:235)
at org.apache.commons.logging.impl.LogFactoryImpl.getInstance(LogFactoryImpl.java:209)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:351)
at org.hibernate.cfg.Configuration.(Configuration.java:110)
… 1 more
Caused by: org.apache.commons.logging.LogConfigurationException: java.lang.NullPointerException (Caused by java.lang.NullPointerException)
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:397)
at org.apache.commons.logging.impl.LogFactoryImpl.newInstance(LogFactoryImpl.java:529)
… 5 more
Caused by: java.lang.NullPointerException
at org.apache.commons.logging.impl.LogFactoryImpl.getLogConstructor(LogFactoryImpl.java:374)
… 6 more
——————————————————————————————-
And i hae made some changes in the cfg.xml and find below my configuration file.
I have used “sun.jdbc.odbc.JdbcOdbcDriver” instead of “com.mysql.jdbc.Driver”
——————————————————–
sun.jdbc.odbc.JdbcOdbcDriver
jdbc:odbc:Connect
sa
sa
10
true
org.hibernate.dialect.SQLServerDialect
update
————————————————
I have kept all the files(2 xml and 2 java) in the same path.
Could any one help me in sort this?
I tried using the transaction. but eclipse does not recognize transaction. how to overcome this?
realy very nice…….. It’s very helpful to me to get an idea at a glance. Thanks for posting…. !!!