tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Hibernate > Basic > First Example

First Example 

The following example shows performing CRUD operations using Hibernate. First we need to configure hibernate.cfg.xml which lets us to specify hibernate dialect, driver class, connection url, user name, password and other hibernate configuration parameters. This configuration file has to be in classpath.

File Name  :  
/HIBERNATE_CRUD_OPS/src/hibernate.cfg.xml 

Create a POJO representing the database table. Each row in the table represents an unique instance of POJO. The database table column names and property names in POJO need not be identical.

Company Table

company_table

Company POJO

File Name  :  
com/bethecoder/tutorials/hibernate/basic/Company.java 
   
package com.bethecoder.tutorials.hibernate.basic;

public class Company {

  private int id;
  private String name;
  private int employeeCount;
  private int projectCount;
  
  private String address1;
  private String address2;
  
  public String getAddress1() {
    return address1;
  }
  public void setAddress1(String address1) {
    this.address1 = address1;
  }
  public String getAddress2() {
    return address2;
  }
  public void setAddress2(String address2) {
    this.address2 = address2;
  }
  public int getEmployeeCount() {
    return employeeCount;
  }
  public void setEmployeeCount(int employeeCount) {
    this.employeeCount = employeeCount;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getProjectCount() {
    return projectCount;
  }
  public void setProjectCount(int projectCount) {
    this.projectCount = projectCount;
  }

  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("{ id = ").append(id).append(", ");
    sb.append("name = ").append(name).append(", ");
    sb.append("employeeCount = ").append(employeeCount).append(", ");
    sb.append("projectCount = ").append(projectCount).append(", ");
    sb.append("address1 = ").append(address1).append(", ");
    sb.append("address2 = ").append(address2).append(" }");
    return sb.toString();
  }
}
   

Create a mapping configuration file mapping column names of table with properties of POJO. Update hibernate configuration with mapping file,

<mapping resource="com/bethecoder/tutorials/hibernate/basic/Company.hbm.xml"/>

File Name  :  
/HIBERNATE_CRUD_OPS/src/com/bethecoder/tutorials/hibernate/basic/Company.hbm.xml 

Get the libraries shown below. hsqldb.jar, mysql.jar and ojdbc14.jar are JDBC drivers for HSQL database, mysql and oracle respectively. For this example we are going with mysql database driver.

hibernate_libs

To make a connection with database we need to configure hibernate session factory which allows us to open a session with database. This utility helps us to configure session factory.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/util/HibernateUtil.java 
   
package com.bethecoder.tutorials.hibernate.basic.util;

import java.util.List;

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

public class HibernateUtil {

  /**
   * Hibernate Session Factory 
   */
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        try {
            //Create SessionFactory from configuration hibernate.cfg.xml
          if (sessionFactory == null) {
            sessionFactory = new Configuration().configure().buildSessionFactory();
          }
        catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
        
        return sessionFactory;
    }

    public static void print(List<?> list) {
      
      if (list == null || list.size() == 0) {
        System.out.println("<Empty>");
      }
      
    for (int i = ;i < list.size() ; i ++ ) {
      System.out.println(list.get(i));
    }
    }
}
   

To following code shows CRUD (Create, Update and Delete) operations using hibernate.

File Name  :  
com/bethecoder/tutorials/hibernate/basic/tests/CrudOpsTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.hibernate.basic.tests;

import java.util.List;
import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class CrudOpsTest {

  public static void main  (String [] args) {
    
    createCompany();    
    listCompanies();
    
    //updateCompany();
    //deleteCompany();
  }
  
  private static void deleteCompany() {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
  
    Company company = (Companysession.load(Company.class, new Integer(2));
    System.out.println(company);
    
    session.delete(company);
    session.getTransaction().commit();
    session.close();

  }
  
  private static void updateCompany() {
    
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
  
    Company company = (Companysession.load(Company.class, new Integer(1));
    System.out.println(company);
    
    company.setAddress1(company.getAddress1() "@");    
    session.update(company);
    System.out.println(company);
    
    session.getTransaction().commit();
    session.close();
  }
  
  private static void listCompanies() {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    List<?> companies = session.createQuery("from Company").list();    
    HibernateUtil.print(companies);
    
    session.getTransaction().commit();
    session.close();
  }
  
  private static void createCompany() {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();

    Company company = new Company();
    company.setName("CFR");
    company.setAddress1("");
    company.setAddress2("add24435");
    company.setEmployeeCount(6478);
    company.setProjectCount(887);    
    session.save(company);    
    session.getTransaction().commit();
    session.close();
    
    System.out.println("Saved successfully...");
  }
}
   



 
  


  
bl  br