Jan 8, 2014

Starting with Hibernate 4.3

Download Hibernate binaries from following url


Create new java project  in Eclipse and set jars from %HIBERNATE_HOME%/lib/required in class-path.  Also get the java connector for database that you  are planning to use and put it in class path of your project.

Also in order to get some good tables with data I downloaded and imported northwind database from following location. This will give us list of tables that we can play with while establishing various relationships.


Now create configuration file hibernate.cfg.xml in src folder of your eclipse project

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
      <session-factory>
            <!-- Database connection settings -->
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql://localhost:3306/northwind</property>
            <property name="connection.username">root</property>
            <property name="connection.password"></property>
            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
      </session-factory>
</hibernate-configuration>
`
So following will be what your eclipse project will look like.


Once these things are ready we will create one utility class that will provide us an instance of HibernateSession and also the same class will have one utility method to close the session. These two methods we will use in our DAO classes for getting and releasing Hibernate Sessions.

package com.techcielo.hibernate43.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {
       public static Session getSession(){
              Session sess = null;
              Configuration config = new Configuration().configure();
              ServiceRegistry serviceRegistry = null;
              StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
              builder.applySettings(config.getProperties());
              serviceRegistry = builder.build();
              SessionFactory sFec = config.buildSessionFactory(serviceRegistry);
              sess = sFec.openSession();
              return sess;
       }
      
       public static void closeSession(Session sess){
              if(sess!=null){
                     try{
                           sess.close();
                     }
                     catch(HibernateException e){
                           //do nothing just silence this exception
                     }
              }
       }
}


Notice that we are using StandardServiceRegistryBuilder class to build the sessionFactory.


Now we will select some entity from northwind database to start with. Following is snapshot of northwind database in MySQL.



So we will start with entity Employee (table: employee)

First we will create a bean class that will have following annotations
@Entity: To tell hibernate that this is a hibernate/persistence entity.
@Table: Map this entity to appropriate database table.
@Id: To assign identifier column by which this entity will be identified.
@Column: To map instance variable of class to appropriate column in database table.

Following is the table structure of table



We will start with simple bean class just to see basics of Hibernate. Later we will make it more complex. So we will use only EmployeeID, FirstName and LastName columns from this table. Following will be our bean class.

package com.techcielo.hibernate43.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="employees")
public class EmployeeBean {
      
       @Id
       @Column(name="EmployeeID")
       private int empId;
      
       @Column(name="FirstName")
       private String fName;
      
       @Column(name="LastName")
       private String lName;

       public int getEmpId() {
              return empId;
       }

       public void setEmpId(int empId) {
              this.empId = empId;
       }

       public String getfName() {
              return fName;
       }

       public void setfName(String fName) {
              this.fName = fName;
       }

       public String getlName() {
              return lName;
       }

       public void setlName(String lName) {
              this.lName = lName;
       }
}

Though almost everything is ready, we are yet to tell hibernate container/api about this class. This we will do by adding following line in our hibernate.cfg.xml file.

<mapping class="com.techcielo.hibernate43.bean.EmployeeBean"/>

So we have 
  • Bean class where values will be stored and passed.
  • Table in database to which class will be mapped
  • Configuration file that has information about what class to be used.
  • Utility class to get and release hibernate session.


Let create a dao class and temporarily have a main method in it (later this will be called from service class) to test if we can get value from database.


package com.techcielo.hibernate43.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.techcielo.hibernate43.bean.EmployeeBean;
import com.techcielo.hibernate43.util.HibernateUtil;

public class EmployeeDAO {
       //Temporary method...later will be removed once call is made from service class.
       public static void main(String[] args) {
              EmployeeDAO dao = new EmployeeDAO();
              EmployeeBean emp = dao.getEmployee(1);
              if(emp!=null){
                     System.out.println(emp.getfName()+" "+emp.getlName());
              }
             
       }
      
       /**
        * Will get the employee id and will return from northwind.employees table
        * @param empId
        * @return
        */
       public EmployeeBean getEmployee(int empId){
              Session sess = null;
              try{
                     sess = HibernateUtil.getSession();
                     return (EmployeeBean) sess.get(EmployeeBean.class, empId);
              }
              catch(HibernateException e){
                     e.printStackTrace();//Later remove this by appropriate logger statement or throw custom exception
              }
              return null;
       }
}


Following will be output of this code.

Jan 08, 2014 2:18:17 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Jan 08, 2014 2:18:17 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.0.Final}
Jan 08, 2014 2:18:17 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 08, 2014 2:18:17 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jan 08, 2014 2:18:17 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jan 08, 2014 2:18:17 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Jan 08, 2014 2:18:17 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Jan 08, 2014 2:18:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jan 08, 2014 2:18:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/northwind]
Jan 08, 2014 2:18:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jan 08, 2014 2:18:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jan 08, 2014 2:18:17 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jan 08, 2014 2:18:17 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jan 08, 2014 2:18:17 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Jan 08, 2014 2:18:17 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jan 08, 2014 2:18:17 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select employeebe0_.EmployeeID as Employee1_0_0_, employeebe0_.FirstName as FirstNam2_0_0_, employeebe0_.LastName as LastName3_0_0_ from employees employeebe0_ where employeebe0_.EmployeeID=?
Nancy Davolio