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



Nice tutorial for beginners ! …
…
Thank you so much
@mithun you will have to start on your own
I want to create a simple game using java, will your help me…?
Nice tutorial….but some errors are occurring while run this code…..
Awesome and cool tutorial. Many Thanks Sir
@laxmi
@Laxmi
I think it is expecting your class under the package “com.hib.example”. Try to create a package with com.hib.example and copy your class in this folder and run it.
@Laxmi
I think it is expecting your class under the package “com.hib.example”. Try to create a package with com.hib.example and copy your class in this folder and run it.
hi,
im begineer to learn hibernate..
wen i excute this code i get output saying
Error: Could not find or load main class com.hib.example
plz help me soon ..
what i have done wrong .. when i dont have any errors..
This is very useful for beginners
@Debt Settlement Help
@WebDev
ok boos
we will be write some new example about other mapping relationship in hibernate
very good titurrial
@Arthur
Hi Arthur the example works for me with all the .jar files in hibernate-distribution-3-6-8-Final and for mysql I use mysql-connector-java-5.1.6-bin.jar best Regards
hi can you send me the jar files used on this example. Even just the list of names i dont know what are those.. I cant add them,,thanks
Aw, this was a really good post. In thought I would like to put in writing like this furthermore – taking time and actual effort to make a extremely good article… but what can I say… I procrastinate alot and by no indicates seem to get something done.
Hi.
I created a project as described in this tutorial.
When I run it, I get “/hibernate.cfg.xml not found”.
What is missing?
I understand it should be in the classpath.
What I don’t understand is how to accomplish this.
It is under “src” directory is compiled into the classes directory. I thought that should do it for the classpath thing. What is missing?
Thank you.
Kirill.
i am trying this code but it giving me error as given below..
126 [main] INFO org.hibernate.annotations.common.Version – Hibernate Commons Annotations 3.2.0.Final
133 [main] INFO org.hibernate.cfg.Environment – Hibernate 3.6.8.Final
134 [main] INFO org.hibernate.cfg.Environment – hibernate.properties not found
138 [main] INFO org.hibernate.cfg.Environment – Bytecode provider name : javassist
141 [main] INFO org.hibernate.cfg.Environment – using JDK 1.4 java.sql.Timestamp handling
201 [main] INFO org.hibernate.cfg.Configuration – configuring from resource: /hibernate.cfg.xml
201 [main] INFO org.hibernate.cfg.Configuration – Configuration resource: /hibernate.cfg.xml
251 [main] WARN org.hibernate.util.DTDEntityResolver – recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
272 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(8) Attribute “name” is required and must be specified for element type “property”.
277 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(9) Attribute “name” is required and must be specified for element type “property”.
277 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(10) Attribute “name” is required and must be specified for element type “property”.
278 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(11) Attribute “name” is required and must be specified for element type “property”.
278 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(12) Attribute “name” is required and must be specified for element type “property”.
278 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(13) Attribute “name” is required and must be specified for element type “property”.
279 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(14) Attribute “name” is required and must be specified for element type “property”.
279 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(15) Attribute “name” is required and must be specified for element type “property”.
280 [main] ERROR org.hibernate.util.XMLHelper – Error parsing XML: /hibernate.cfg.xml(16) The content of elements must consist of well-formed character data or markup.
Exception in thread “main” java.lang.NullPointerException
at MyExample.main(MyExample.java:28)
Could not parse configuration: /hibernate.cfg.xml
please suggest.
very nice article! great for a beginner! gives a fantastic overview!!!
Great artical, but Persisting Class cannot read.
Meanwhile I found some nice article for hibernate beginners.
Hibernate Tutorial for Beginners
Hi,
Excellent Post. Plz write something on Hibernate One-TO-One, One-To-Many, Many-To-Many Relations.
As a begginer it ‘s very useful for me
realy very nice…….. It’s very helpful to me to get an idea at a glance. Thanks for posting…. !!!
I tried using the transaction. but eclipse does not recognize transaction. how to overcome this?
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?
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.
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.
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
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,
@robbie70 Thanks for your code input. I am sure other readers will benefit from your contribution.
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();
}
}
}
Very easy and well formed tutorial. I had some issues with quotes thing because of copy paste but overall best tutorials for beginners.
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.
@remy2France I am glad you liked it. Thanks for adding the code for transactions. I am sure others would benefit from 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”);
@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.
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.
@Vinay
Hi,
flush doesn’t work for me too. How do I specify transaction begin and end ?? (I have no Spring either)
thanks.
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
Transaction had not been put here because they are managed in service layer through Spring. Sorry about that.
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.
Great stuff to get going , Thanks !
@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.
There is no “name” attribute in any “property” element in hibernate.cfg.xml
@Virendra
Thanks Virendra. I am glad you liked it.
@hoodia gordonii
Hoodia , can you help in pointing out what is missing so that we can update accordingly ?
awesome tutorials as per me. really very helpfull for the begginer with hibernate.
thanks a lot.
best wishes to all.
Nice but i think something is missing.
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.