Writing First Hibernate Code

In this section I will show you how to create a simple program to insert record in MySQL database. You can run this program from Eclipse or from command prompt as well. I am assuming that you are familiar with MySQL and Eclipse environment.

Ads

Tutorials   
Hibernate envers custom revinfo table Hibernate 5 Envers Hibernate Envers get all revisions Hibernate Examples Hibernate 5 build SessionFactory Example Hibernate 5 SessionFactory Example Hibernate 5 Annotation Example How to download Hibernate 5.x? Hibernate 5 Features Hibernate 5 Tutorials Learning Hibernate ORM - Free Training/Tutorial videos of Hibernate ORM with Java How to write hello world example program in Hibernate? How to create one to one relationship in Hibernate 4 with Annotation? How to calculate minimum in Hibernate using the min() Function Hibernate ORM 4.2.21.Final Released - Create CURD application in latest Hibernate Hibernate ORM 4.2.21 Tutorial - Learn Hibernate ORM Framework Hibernate Error: Failed to create sessionFactory object.java.lang.NoClassDefFoundError How to create Hibernate Project in Eclipse? Examples of Hibernate Criteria Query Hibernate ORM 4.3.6.Final released Hibernate ORM 4.2.14.Final released Hibernate 4.3.4 Released: Hibernate 4.3.4.Final Maven dependency Hibernate association and join example Learn Hibernate programming with Examples Introduction to Hibernate Framework Hibernate Tutorial: Learn Hibernate with examples Hibernate 4.3 Hello World: Example Hibernate ORM 4.3.1.Final released How to create SessionFactory in Hibernate 4.3.1? Hibernate 4 Hello World: Example of Hello World program Hibernate 4 create Session Factory: Example of creating Session Factory in Hibernate 4 Hibernate 4.3 and JPA 2.1 Example What is Hibernate in Java? Hibernate Overview and Architecture What is JPA 2.1? Hibernate 4.3.0.Final Maven dependency Hibernate 4.3 ORM Features Hibernate 4.3 Tutorial Hibernate Criteria average example Hibernate Criteria load all objects from table Hibernate Criteria Hibernate ORM 4.3.0.Final released Hibernate beginner tutorial Hibernate Session.delete() Example Hibernate save or update method example Hibernate Load Example Hibernate save Example - Rose India Hibernate 4 tutorials Hibernate Example Step by Step in Eclipse Hibernate Configuration files Setup Hibernate Environment
Ads

Writing First Hibernate Code

     

In this section I will show you how to create a simple program to insert record in MySQL database. You can run this program from Eclipse or from command prompt as well. I am assuming that you are familiar with MySQL and Eclipse environment.

Configuring Hibernate
In this application Hibernate provided connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.

Here is the latest video tutorial of writing Hibernate application which is developed using the Hibernate 4. In this video tutorial you will learn the latest method of writing Hibernate code.

Here is the video tutorial of "How to create Hibernate 4 Hello World Program?":

Here is the code:

<?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 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">root</property>
  <property name="hibernate.connection.password"></property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Mapping files -->
  <mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

In the above configuration file we specified to use the "hibernatetutorial" which is running on localhost and the user of the database is root with no password. The dialect property  is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database. Hibernate supports many database. With the use of the Hibernate (Object/Relational Mapping and Transparent Object Persistence for Java and SQL Databases),  we can use the following databases dialect type property:

  • DB2 - org.hibernate.dialect.DB2Dialect
  • HypersonicSQL - org.hibernate.dialect.HSQLDialect
  • Informix - org.hibernate.dialect.InformixDialect
  • Ingres - org.hibernate.dialect.IngresDialect
  • Interbase - org.hibernate.dialect.InterbaseDialect
  • Pointbase - org.hibernate.dialect.PointbaseDialect
  • PostgreSQL - org.hibernate.dialect.PostgreSQLDialect
  • Mckoi SQL - org.hibernate.dialect.MckoiDialect
  • Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect
  • MySQL - org.hibernate.dialect.MySQLDialect
  • Oracle (any version) - org.hibernate.dialect.OracleDialect
  • Oracle 9 - org.hibernate.dialect.Oracle9Dialect
  • Progress - org.hibernate.dialect.ProgressDialect
  • FrontBase - org.hibernate.dialect.FrontbaseDialect
  • SAP DB - org.hibernate.dialect.SAPDBDialect
  • Sybase - org.hibernate.dialect.SybaseDialect
  • Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

The <mapping resource="contact.hbm.xml"/> property is the mapping for our contact table.

Writing First Persistence Class
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for Contact.java:

package roseindia.tutorial.hibernate;

/**
 @author Deepak Kumar
 *
 * Java Class to map to the datbase Contact Table
 */
public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

  /**
 @return Email
 */
  public String getEmail() {
  return email;
  }

  /**
 @return First Name
 */
  public String getFirstName() {
  return firstName;
  }

  /** 
 @return Last name
 */
  public String getLastName() {
  return lastName;
  }

  /**
 @param string Sets the Email
 */
  public void setEmail(String string) {
  email = string;
  }

  /**
 @param string Sets the First Name
 */
  public void setFirstName(String string) {
  firstName = string;
  }

  /**
 @param string sets the Last Name
 */
  public void setLastName(String string) {
  lastName = string;
  }

  /**
 @return ID Returns ID
 */
  public long getId() {
  return id;
  }

  /**
 @param l Sets the 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. 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="roseindia.tutorial.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </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>

Setting Up MySQL Database
In the configuration file(hibernate.cfg.xml) we have specified to use hibernatetutorial database running on localhost.  So, create the databse ("hibernatetutorial") on the MySQL server running on localhost.

Developing Code to Test Hibernate example
Now we are ready to write a program to insert the data into database. We should first understand about the Hibernate's Session. 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:

session.save(contact)

Here is the code of FirstExample.java


package roseindia.tutorial.hibernate;

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


/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Hibernate example to inset data into Contact table
 */
public class FirstExample {
  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("Deepak");
  contact.setLastName("Kumar");
  contact.setEmail("[email protected]");
  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();

  }
  
  }
}

In the next section I will show how to run and test the program.

Advertisements

Ads
Share on Google+Share on Google+

Writing First Hibernate Code

Posted on: January 8, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Writing First Hibernate Code   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:41
dibya jyoti das
November 19, 2012
The code is amaizing

This tutorial is very simple as well asa very effective.
sahad
November 28, 2012
Please answer

I cant get the output by using above code.I am getting the error Could not parse mapping document from resource contact.hbm.xml Exception in thread "main" java.lang.NullPointerException at roseindia.FirstExample.main(FirstExample.java:34)
Bhajan
January 4, 2013
Need to make small correction in the given example

Hi There, No doubt, your this tutorial (http://www.roseindia.net/hibernate/firstexample.shtml) is very good and informative. But when I tried to use above example as it is, It was not working. I would like to give you my updated code, You can review this and if find this relevant than please update this example. 1.) Need to create object of transaction class as below after session creation. org.hibernate.Transaction txn = session.beginTransaction(); txn.begin(); 2.) Need to commit transaction after save command as: session.save(<NAME_OF_OBJECT>); txn.commit();
vidushe
April 3, 2013
unable to run the code

i tried your program.its giving me the 'hibernate.cfg.xml' file not found error.while debugging, i noticed that the code after SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); is not being executed. pls help
joseph
April 13, 2013
small issue with sample code

Hey, Nice and simple article I tried your example.It works good but FirstExample.java fails to insert to database.I am using SqlServer 2005 <property name ="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property> <property name ="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> From the logs I can see that the INSERT statement is getting created fine and no exceptions are present but still no entry in database,any ideas?
Dilip Voruganti
April 28, 2013
Data is not going to be inserted in this example

Total example is correct but data is not going to be inserted bcoz of, Not opening Transaction. i.e.., After session =sessionFactory.openSession(); INSERT Transaction t =session.beginTransaction(); and at last say t.commit(); Then ur data will be inserted into the database.
Saurabh
July 10, 2013
Missing code

In FirstExample class we need to begin the Transaction after opening the session i,e Transaction trx=session.beginTransaction(); statement after session =sessionFactory.openSession(); and commit the transaction after saving the session i,e trx.commit(); Correct code ---------------------------- package com.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class FirstExample { 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"); Transaction trx=session.beginTransaction(); Contact contact = new Contact(); contact.setId(3); contact.setFirstName("Deepak"); contact.setLastName("Kumar"); contact.setEmail("[email protected]"); session.save(contact); trx.commit(); System.out.println("Done"); }catch(Exception e){ System.out.println(e.getMessage()); }finally{ // Actual contact insertion will happen at this step session.close(); } } }
rambharath
February 7, 2014
test mail

this too easy to understand for beginners.....tnks a lot.....
Meena Patel
September 2, 2013
Error

Could not parse mapping document from resource employee.hbm.xml Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource employee.hbm.xml Exception in thread "main" java.lang.NullPointerException at com.hibtutorial.mypackage.StoreData.main(StoreData.java:22)

Ads

 

Ads