Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions? | Software Development
 

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.

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 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("deepak_38@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();

      }
    
  }
}

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

 

                         

» View all related tutorials
Related Tags: sql c hibernate api com inheritance session class collections table binding parameters object bugs io connection classes focus object-oriented polymorphism

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

150 comments so far (
post your own) View All Comments Latest 10 Comments:

After using Transaction tx=session.beginTransaction();
tx.commit();
Still the same prob exists. plz tel a solution

Exception in thread "main" java.lang.NoClassDefFoundError: FirstExample (wrong n
ame: roseindia/tutorial/hibernate/FirstExample)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
4)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)

Thanks in advance
vaidya

Posted by vaidyanathan on Thursday, 01.21.10 @ 15:27pm | #94205

This site contians lot of programming stuff that helps developers and students.

Posted by utpal on Wednesday, 01.20.10 @ 13:56pm | #94173

Exception in thread "main" org.hibernate.HibernateException: Hibernate Dialect must be explicitly set

No one had given proper answer to resolve this error

Posted by Bala on Tuesday, 01.19.10 @ 11:05am | #94131

session.beginTransaction().commit();

Add this after session.save(contact);

it will work

Posted by parth on Friday, 12.11.09 @ 11:20am | #93284

I am getting null pointer exception at SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Can anyone help me?

Posted by Ranjith on Thursday, 08.27.09 @ 16:00pm | #90356

I too get the same exception. could any1 please explain on this

Thanks

Posted by Sharadha on Thursday, 04.9.09 @ 17:28pm | #86688

this is excelent

thanks for this

Posted by raghava on Tuesday, 12.16.08 @ 12:13pm | #82837


After
session.save(contact);
add
session.beginTransaction().commit();
or
session.connection().commit();

I think it will solve ur problem

Posted by mahesh on Wednesday, 12.3.08 @ 22:21pm | #82347

to the dudes having NPE - additional libraries are required:
antlr-2.7.6.jar,commons-collections-3.1.jar,commons-logging.jar,dom4j-1.6.1.jar,javassist-3.4.GA.jar,jta-1.1.jar,slf4j-api-1.5.3.jar,slf4j-jcl-1.5.3.jar

see hibernate distribution

Posted by Tom on Monday, 10.6.08 @ 16:30pm | #80927

NO INSERTION HAPPENS!!

System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak");
session.save(contact);
System.out.println("Done");
}catch(Exception e){
System.out.println("in Exception");
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
System.out.println("the finally block");
session.flush();
session.close();
System.out.println("out of finally");
}

HIBNERNATE CFG:

<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@10.20.169.171:1521:CFSDEV </property>
<property name="hibernate.connection.username">Cfs_sas</property>
<property name="hibernate.connection.password">cfs123</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect"> org.hibernate.dialect.OracleDialect </property>

<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>

Posted by Sanket on Wednesday, 09.24.08 @ 16:52pm | #80660

 
Tell A Friend
Your Friend Name

 

 
Recently Viewed
Software Solutions
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.