Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
Hibernate
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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.

 

                         

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

Current Comments

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

Im runing this example in my struts application ..,

when it reach this line , im getting nullpointer exception ..,
pls help me out of this..

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

[8/12/08 13:55:48:266 IST] 65502792 RequestProces W org.apache.struts.action.RequestProcessor Unhandled Exception thrown: class java.lang.NullPointerException
[8/12/08 13:55:49:234 IST] 65502792 WebGroup E SRVE0026E: [Servlet Error]-[]: java.lang.NullPointerException

Thanks
Mani

Posted by Mani on Tuesday, 08.12.08 @ 14:05pm | #72478

Make slight modification to code to insert data into DB.Otherwise it will only be in session.

In FirstExample.java

Contact contact = new Contact();
contact.setId(3);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("deepak_38@yahoo.com");
Transaction tx = session.beginTransaction();
session.save(contact);
tx.commit();
System.out.println("Done");

In contact.hbm.xml change class "assigned" to "increment"

<id name="id" type="long" column="ID" >
<generator class="increment"/>
</id>

Posted by Sanjiv bhargava on Thursday, 06.12.08 @ 19:26pm | #63125

what to write in the Driver name if we are using Oracle database

Posted by naresh on Wednesday, 06.11.08 @ 10:47am | #62998

hell sir
when i am executing the FirstExample in struts
it is showing nullpointer exception..can you give the solution for this..

Posted by suresh on Wednesday, 05.28.08 @ 14:20pm | #61264

hi.... I use the above code to run my project but it showed me following error: log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. entity class not found: Student But the Student class is present. Even i did mapping in hibernate.cfg.xml The Person.hbm.xml file is: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated May 12, 2008 11:13:52 AM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Person" table="person" catalog="test"> <id name="personId" type="int"> <column name="personId" /> <generator class="assigned" /> </id> </class> </hibernate-mapping> and the Student.hbm.xml file is: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated May 12, 2008 11:13:52 AM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="Student" table="student" catalog="test"> <id name="studentId" type="int"> <column name="studentId" /> <generator class="assigned" /> </id> <property name="studentName" type="string"> <column name="studentName" length="20" /> </property> <property name="studentAge" type="java.lang.Integer"> <column name="studentAge" /> </property> <property name="personId" type="java.lang.Integer"> <column name="personId" /> </property> </class> </hibernate-mapping>

Posted by Anita on Monday, 05.12.08 @ 22:57pm | #59515

If you r a beginer then plz do not forget to add c:\hibernate-3.2\lib\*.jar files to your class path variable.
Otherwise Main method will how errors.

Posted by Amit Ruhil on Sunday, 04.27.08 @ 21:19pm | #58002

While i am running the FirstExample.java file runas javaApplication it is showing
Dialect class not found:
java.lang.NullPointerException
at src.com.FirstExample.main(FirstExample.java:29)
Exception in thread "main"

Error.so how can i solve this. Can anyone needful to me..

Posted by Naveen on Wednesday, 04.23.08 @ 18:36pm | #57704

Hi,
Based on the example given , I'm trying to run my application using Hibernate 2.1. But I'm getting exception net.sf.hibernate.MappingException : Error reading Resource Employee.hbm.xml.

I have my hibernate.cfg.xml and Employee.hbm.xml in project/bin/ folder as suggested.

My Employee.hbm.xml is as follows
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "Sun/Workspace/HibernateExample/Sun/Workspace/HibernateExample/hibernate-mapping-2.0.dtd" >
<hibernate-mapping>
<class name="com.hibernate.Employee" table="Employee">
<id name="empID" type="Integer" column="EmpID">
<generator class="assigned"></generator>
</id>
<property name="dob">
<column name="DOB"/>
</property>
<property name="empName">
<column name="EmpName"/>
</property>
<property name="salary">
<column name="Salary"/>
</property>
</class>
</hibernate-mapping>

and my hibernate.cfg.xml is as follows
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory name="MyFactory">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/MySQL</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Please do guide me in getting this resolved.

Posted by Ravi on Monday, 03.31.08 @ 08:21am | #54848

hi

i'm trying to do the firstexample of hybernate.but i'm recieving the message as follows

Inserting Record
Hibernate: insert into CONTACT (FNAME, LNAME, EMAIL) values (?, ?, ?)
Done


data is not inserted in to record..and no error or exceptin message

Posted by Dhanushka Jayathilaka on Tuesday, 03.18.08 @ 18:23pm | #53198

Hello RoseIndia Team / Deepak Kumar,

Please include begin transaction and commit transaction statements in FirstExample.java to save the data in the database.
---------------------------------------------
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();//This line is Missing in the example.

session.save(contact);
tx.commit();//Missing in the example.
----------------------------------------------

As per the example the datas doesn't get save in the database and beginners have to struggle a lot.
I hope you will do the needful ASAP.
Thank you,
Suraj Gupta

Posted by Suraj Gupta on Tuesday, 03.18.08 @ 17:09pm | #53185

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

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.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

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 © 2007. All rights reserved.