Friday, April 6, 2012

Hibernate Beginners Tutorial

This simple tutorial specially for beginners of Hibernate and who are planing to use NetBeans IDE for their Hibernate project.
Hibernate is an object-relational mapping (ORM) library for the Java language. In this tutorial I'm going to illustrate how we can easily map java objects with relational database using Hibernate. I have used NetBeans IDE for this task because complete version of NetBeans comes with all the tools needed. No additional downloads. First you need to download NetBeans and MySQL server
Download NetBeans (Download NetBeans bundle with all packs)
Download MySQL Server (Note : You can also use WAMP Server or any other server environment with MySQL if you like)

To complete this tutorial we need MySQL server & NetBeans installed. I have used MySQL server 5.5 & NetBeans 7.1.

First we have to create a database. I have a simple MySQL database with single table. I'm going to use that database for the tutorial.
Here are the codes for create the database. You can use this database or your own database.

1. Create the database
CREATE DATABASE retailer;

1.1 Create table customers
CREATE TABLE customers(
name varchar(20),
C_ID int NOT NULL AUTO_INCREMENT,
address  varchar(20),
email varchar(50),
PRIMARY KEY(C_ID)
);

2. Creating the java program

2.1. Create new java application.

File > New project > Java > Java Application > Next
Name it as HibernateTest. Then click Finish to create the project.

2.2. Create a POJO class

Hibernate use java classes to map to the relational databases. These classes are called POJO(Plain Old Java Objects) classes. Here we are going to create a POJO class
Right click the package (hibernatetest) & select New > Java Class
Name it as Customer. Click Finish to create the class.(Don't change the main class)
We have to use variables to map with the database columns.

Here is the code for POJO class
package hibernatetest;

/**
 *
 * @author Chathura
 */
public class Customer {
    private String customerName;
    private int customerID;
    private String customerAddress;
    private String customerEmail;

    public void setCustomerAddress(String customerAddress) {
        this.customerAddress = customerAddress;
    }

    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    public void setCustomerID(int customerID) {
        this.customerID = customerID;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerAddress() {
        return customerAddress;
    }

    public String getCustomerEmail() {
        return customerEmail;
    }

    public int getCustomerID() {
        return customerID;
    }

    public String getCustomerName() {
        return customerName;
    }
}

To generate getters and setters easily in NetBeans, right click on the code and  select Insert Code Then choose Getter... or Setter...

Variable customerName will map with the name column of the customers table.
Variable customerID will map with the C_ID column of the customers table. It is integer & auto incremented. So POJO class variable also should be int.
Variable customerAddress will map with the address column of the customers table.
Variable customerEmail will map with the email column of the customers table.

Then we have to connect to the database we have already created. In my case it is retailer.
(Before doing this we have to connect NetBeans with MySQL)
(Afret connecting NetBeans with MySQL start the server.)

Select Services tab lying next to the Projects tab.
Expand Databases. Expand MySQL Server. There we can see the all databases on MySQL sever


Right click the database retailer. Select Connect...

3. Creating the configuration XML

Hibernate need a configuration file to create the connection.
Right click package hibernatetest select New > Other > Hibernate > Hibernate Configuration Wizard  Click Next
In next window click the drop down menu of Database Connection and select retailer database connection.


Click Finish to create the file.

Here is the complete code for configuration file.


  
    com.mysql.jdbc.Driver
    jdbc:mysql://localhost:3306/retailer
    root
    chathura
    10
    org.hibernate.dialect.MySQLDialect
    thread
    org.hibernate.cache.NoCacheProvider
    true
    update
    
  

Highlighted lines 5 and 6 configure the database password and username. Replace those properties according to your database.
Line 13 :
<mapping resource="customersmapping.hbm.xml"/>
My configuration and mapping documents are in the same package. If they are not in the same package we have to use packagename.mapping document name.hbm.xml

4. Creating the mapping file

Mapping file will map relevant java object with relevant database table column.
Right click project select New > Other > Hibernate > Hibernate Mapping Wizard  click Next name it as customersmapping.hbm click Next
Next window we have to select Class to Map and Database Table.

Select a class to map




After selecting correct class click OK

Select Database Table
Click drop down list and select the table you want to map.
Code for mapping file.

  
  
  
  
  
  
  
  
  
  
  
  
  
  


Here
Line 2 :
<class name="hibernatetest.Customer" table="customers">

class name = packagename.classname
table = table we are going to map with java class
Line 3 & 4 :
<id column="C_ID" name="customerID" type="int">
  <generator class="native">

id column = primary key column of the table
name = variable name of the POJO class which maps with the primary key of the table
type = type of the primary key
generator class = if you are using auto increment primary key use "native" other vice it should be "assigned"
Line 6 & 7 :
<property name="customerName">
  <column name="name">

property name = variable name of the POJO class
column name = database column that maps with previous variable

To populate the database you can use this sample code.
package hibernatetest;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Chathura
 */
public class HibernateTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Session session = null;
    try{
        SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
        session =sessionFactory.openSession();
        session.beginTransaction();
        
        System.out.println("Populating the database !");
        Customer customer = new Customer();
        customer.setCustomerName("Chathura");
        customer.setCustomerAddress("221B,Moratuwa");
        customer.setCustomerEmail("priyankarahac@gmail.com");
        
        session.save(customer);
        session.getTransaction().commit();
        
        System.out.println("Done!");
        }
    
    catch(Exception e){
        System.out.println(e.getMessage());
    }
 
  finally{
    session.flush();
    session.close();
  }
 }
}

Part of the output.

 

To retreave values we have to use HQL statements.
Here is a sample code for retrieve values from the table where customer id  = 2
package hibernatetest;

import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Chathura
 */
public class HibernateTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Session session = null;
    try{
        SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
        session =sessionFactory.openSession();
        session.beginTransaction();
   
        String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";
        org.hibernate.Query query = session.createQuery(HQL_QUERY);
        //Prepared statement
        query.setParameter("customerId",2);
        System.out.println("Reading values");
         for(Iterator it=query.iterate();it.hasNext();){
             Customer customer = (Customer) it.next();
             System.out.println(customer.getCustomerName());
             System.out.println(customer.getCustomerAddress());
             System.out.println(customer.getCustomerEmail());
             System.out.println(customer.getCustomerID());
             
            }
        session.getTransaction().commit();
        System.out.println("Done!");
        }
    
    catch(Exception e){
        System.out.println(e.getMessage());
    }
 
  finally{
    session.flush();
    session.close();
  }
 }
}
Line 23 :
String HQL_QUERY ="from Customer customers where customers.customerID = :customerId";

Customer = class name
customers = table name
customers.customerID = table name.javavariable name

Result :


You can download sample project here
Password : hibernatetest

If you find this post helpful don't forget to leave a comment. Your comments always encourage me to write more!

22 comments:

  1. Good job...No words to express...expecting more from you.

    ReplyDelete
  2. Thanks, great demo ! Please let me know delete and update also. Faculty at Hoven - http://www.hoven.in

    ReplyDelete
  3. Thanks, great demo ! Please let me know delete and update also. Faculty at Hoven - http://www.hoven.in

    ReplyDelete
  4. great demo.
    how to insert,update and delete derby table using netbean with jsf??????
    plz publish demo if possible like above demo.

    thanks in advance.

    ReplyDelete
  5. when i tried to ececute by the above way i got an exception Could not parse mapping document from resource customersmapping.hbm.xml wt does it mean.

    ReplyDelete
  6. Great job, you explained very clearly for some one to follow your instruction to complete the demo, thank you,

    ReplyDelete
  7. Great job, you explained very clearly for some one to follow your demo, even for someone with no Hibernate experience,

    ReplyDelete
  8. great great.t'was enlightening. more pls..tnx.

    ReplyDelete
  9. High ranking provides you essentially the most qualified traffic.
    Sometimes it's because their theme does not give them a choice; sometimes, it's since they don't know they have a very choice or have no idea of why they want one. When wanting to increase your building backlinks remember that the greater inbound links you receive the better, but quality is always better than quantity.
    Look at my webpage ; http://proimblogger.com/captcha-sniper-review/

    ReplyDelete
  10. please correct your spelling in right panel.
    which is having "Android HtttpClient".
    in that there should be only two "tt".
    please correct it.

    ReplyDelete
  11. its Really good example Thankx

    ReplyDelete
  12. thanks a lot. it is so simple but clear.finally, i can understand how hibernate works.

    ReplyDelete
  13. Thanks a lot. Really simple and helpful

    ReplyDelete
  14. Its really simple and helpful!

    ReplyDelete
  15. nice ...can you post an example for spring hibernate integration using netbeans..

    ReplyDelete
  16. HTML tutorial for beginners with examples

    Free online HTML tutorial for beginners with examples - HTML tutorial will help you in creating website, after study the tutorial you will just one step ahead of creating your own website. HTML is easy to understand and you will enjoy it to learn. HTML tutorial contains hundreds of examples to better understand.

    http://www.willvick.com/
    http://www.willvick.com/HTML-tutorial-for-beginners-with-examples/HTML-tutorial-for-beginners-with-examples.aspx

    ReplyDelete