Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > First Hibernate Tutorial –Get Hands on Experience -Part I

First Hibernate Tutorial –Get Hands on Experience -Part I

Part - II >>

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.

  1. Requirements:Eclipse 3, Mysql Database, JDK 1.5, Download hibernate from https://www.hibernate.org/30.html and unzip it.
  2. Setting Up Project :

Step 1: Create project.Open Project Wizard and create simple java project

tutorial1

Next Screen -> New Java Project Screen appears. Enter Project Name.

tutorial2

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

tutorial4

Select Libraries

tutorial5

Click Add Library -> User Librarytutorial6

Click Next

tutorial7

Click userlibraries

tutorial8

Click New Button to create new userlibrary

tutorial9

You can see HibernateLib library created

tutorial10

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

tutorial11

Select all jars and click open. You can see jars being selectd as below:

tutorial12

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

Part - II

Be Sociable, Share!
  1. May 28th, 2013 at 05:51 | #1

    Nice Tutorial..

  2. Suresh
    November 21st, 2012 at 09:27 | #2

    Nice tutorial for beginners ! …
    Thank you so much :)

  3. October 8th, 2012 at 12:31 | #3

    @mithun you will have to start on your own

  4. mithun
    October 7th, 2012 at 23:53 | #4

    mithun :
    I want to create a simple game using java, will your help me…? I am waiting for your valuable replay.

  5. mithun
    October 7th, 2012 at 23:52 | #5

    I want to create a simple game using java, will your help me…?

  6. mithun
    October 7th, 2012 at 23:50 | #6

    Nice tutorial….but some errors are occurring while run this code…..

  7. naveen vodapally
    August 22nd, 2012 at 05:31 | #7

    Awesome and cool tutorial. Many Thanks Sir

  8. Venu
    August 2nd, 2012 at 05:27 | #8

    @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.

  9. Venu
    August 2nd, 2012 at 05:26 | #9

    @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.

  10. laxmi
    July 13th, 2012 at 14:21 | #10

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

  11. yvreddy
    June 29th, 2012 at 05:39 | #11

    This is very useful for beginners

  12. yvreddy
    June 29th, 2012 at 05:37 | #12

    sbt :
    @Vinay
    Hi,
    flush doesn’t work for me too. How do I specify transaction begin and end ?? (I have no Spring either)
    thanks.

    @Debt Settlement Help

  13. abhishek
    June 16th, 2012 at 00:19 | #13

    @WebDev
    ok boos
    we will be write some new example about other mapping relationship in hibernate

  14. Arun
    June 11th, 2012 at 00:30 | #14

    very good titurrial

  15. George Ojiwa
    June 9th, 2012 at 05:31 | #15

    @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

  16. Arthur
    April 2nd, 2012 at 02:17 | #16

    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

  17. February 15th, 2012 at 07:07 | #17

    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.

  18. Kirill
    December 18th, 2011 at 11:07 | #18

    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.

  19. Dharmendra Bhuva
    December 18th, 2011 at 09:51 | #19

    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.

  20. swathi
    July 13th, 2011 at 14:49 | #20

    very nice article! great for a beginner! gives a fantastic overview!!!

  21. Keith
    March 20th, 2011 at 14:39 | #21

    Great artical, but Persisting Class cannot read.
    Meanwhile I found some nice article for hibernate beginners.
    Hibernate Tutorial for Beginners

  22. January 17th, 2011 at 03:42 | #22

    Hi,

    Excellent Post. Plz write something on Hibernate One-TO-One, One-To-Many, Many-To-Many Relations.

  23. Josuva
    October 6th, 2010 at 09:45 | #23

    As a begginer it ‘s very useful for me

  24. Amit
    July 21st, 2010 at 07:54 | #24

    realy very nice…….. It’s very helpful to me to get an idea at a glance. Thanks for posting…. !!!

  25. youze
    May 25th, 2010 at 04:22 | #25

    I tried using the transaction. but eclipse does not recognize transaction. how to overcome this?

  26. Bala
    April 29th, 2010 at 23:44 | #26

    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?

  27. March 18th, 2010 at 09:27 | #27

    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.

  28. Mr Wizard
    March 18th, 2010 at 07:01 | #28

    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.

  29. Aukemid
    March 4th, 2010 at 04:33 | #29

    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

  30. Charlie
    February 27th, 2010 at 17:56 | #30

    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,

  31. February 21st, 2010 at 15:02 | #31

    @robbie70 Thanks for your code input. I am sure other readers will benefit from your contribution.

  32. robbie70
    February 21st, 2010 at 10:19 | #32

    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();
    }
    }
    }

  33. shweta
    February 3rd, 2010 at 18:18 | #33

    Very easy and well formed tutorial. I had some issues with quotes thing because of copy paste but overall best tutorials for beginners.

  34. Omie1KnoB
    December 24th, 2009 at 09:56 | #34

    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.

  35. November 14th, 2009 at 11:35 | #35

    @remy2France I am glad you liked it. Thanks for adding the code for transactions. I am sure others would benefit from it.

  36. remy2france
    November 12th, 2009 at 15:06 | #36

    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”);

  37. November 5th, 2009 at 08:31 | #37

    @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.

  38. sbt
    November 5th, 2009 at 05:16 | #38

    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.

  39. sbt
    November 5th, 2009 at 05:11 | #39

    @Vinay
    Hi,

    flush doesn’t work for me too. How do I specify transaction begin and end ?? (I have no Spring either)

    thanks.

  40. November 1st, 2009 at 08:05 | #40

    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

  41. October 9th, 2009 at 12:10 | #41

    Transaction had not been put here because they are managed in service layer through Spring. Sorry about that.

  42. hyperhiber
    October 9th, 2009 at 12:06 | #42

    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.

  43. hyperhiber
    October 9th, 2009 at 12:03 | #43

    Great stuff to get going , Thanks !

  44. smitha
    October 4th, 2009 at 23:55 | #44

    @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.

  45. Goran
    September 27th, 2009 at 16:59 | #45

    There is no “name” attribute in any “property” element in hibernate.cfg.xml

  46. September 10th, 2009 at 19:00 | #46

    @Virendra
    Thanks Virendra. I am glad you liked it.

  47. September 10th, 2009 at 19:00 | #47

    @hoodia gordonii
    Hoodia , can you help in pointing out what is missing so that we can update accordingly ?

  48. Virendra
    September 10th, 2009 at 01:38 | #48

    awesome tutorials as per me. really very helpfull for the begginer with hibernate.
    thanks a lot.

    best wishes to all.

  49. August 28th, 2009 at 14:59 | #49

    Nice but i think something is missing.

  50. August 15th, 2009 at 10:49 | #50

    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.

  1. August 7th, 2009 at 02:01 | #1
  2. August 15th, 2009 at 11:20 | #2
  3. August 17th, 2009 at 14:39 | #3
  4. August 29th, 2009 at 11:09 | #4
  5. August 29th, 2009 at 11:11 | #5
  6. October 6th, 2009 at 01:01 | #6
  7. June 6th, 2012 at 06:29 | #7

Get Adobe Flash playerPlugin by wpburn.com wordpress themes