First Hibernate Tutorial –Get Hands on Experience -Part I

Posted: October 26, 2011 in Java Posts
Tags:

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 fromhttps://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>
com.mysql.jdbc.Driver
jdbc:mysql://localhost/HibernateTest
<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

Advertisements
Comments
  1. You should take part in a contest for one of the best blogs on the web. I will recommend this site!

    Like

  2. Malinda Insogna says:

    Hello There. I found your blog using msn. This is a very well written article. I’ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will certainly comeback.

    Like

  3. Willis says:

    Terrific work! This is the type of information that should be shared around the internet. Shame on the search engines for not positioning this post higher! Come on over and visit my web site . Thanks =)

    Like

  4. Maureen says:

    I simply wanted to post a message to say thanks to you for some of the fabulous advice you are showing on this site. My long internet search has finally been paid with excellent suggestions to go over with my friends. I would believe that many of us readers actually are unquestionably fortunate to live in a magnificent network with many brilliant individuals with very beneficial basics. I feel somewhat lucky to have used your entire webpages and look forward to many more fun moments reading here. Thanks a lot again for everything.

    Like

  5. wstążka says:

    Fantastic web site. A lot of useful info here. I am sending it to some friends ans also sharing in delicious. And of course, thanks for your effort!

    Like

  6. Moja strona says:

    I just couldn’t depart your website prior to suggesting that I really enjoyed the standard information a person provide for your visitors? Is gonna be back often in order to check up on new posts

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s