hbm2ddl HibernateSessionFactory Hibernate


hbm2ddl HibernateSessionFactory

Second Program on Hibernate – Employee

Note: It is advised to though the previous first Program – Student as this is continuation of the previous where new features are added.

The new features in this program are:

  1. Creating table (by name Employee) in the database using hbm2ddl.auto option (in the first program, we have created our own table (called school) in the database, now Hibernate creates Employee table automatically for us).
  2. Writing the properties show_sql etc. and mapping the file hbm.xml from the wizard (in the first program, this is typed manually in the XML file).
  3. All the programs are placed in our own package snrao (earlier placed in the default package of MyEclipse).
  4. Creating HibernateSessionFactory through wizard; we use this in client program (earlier in Student program, SessionFactory is created through coding using buildSessionFactory() in client program. Now we go for Session object directly).

Important Note: The two XML files, cfg and hbm must be either in src folder or in your own package.

The screens are the same (of Student) upto just before "Adding Hibernate Capabilities".

Fields in the Employee class are

int empid;
String empname;
double empsalary;
long empmobile;

I intentionally took different data types to know what columns are created with what data types in the table by Hibernate automatically. I observed when the client program is executed, at the end, Hibernate created a table Employee (on the name of the class) itself with the following columns (on the names of fields) and SQL data types; see the screen. empid is chosen as primary key.

image

In this application, all the bean and client programs are placed in a package called snrao. It is very necessary to create HibernateSessionFactory (the default one) in the package, it is here snrao.

Create the bean program as you did in the previous First Program: Student. Following is the code generated automatically by Hibernate (when only fields are given).

package snrao;
public class Employee 
{
  private int empid;
  private String empname;
  private double empsalary;
  private long empmobile;

  public Employee() 
  {
    // TODO Auto-generated constructor stub
  }
  public int getEmpid() 
  {
    return empid;
  }
  public void setEmpid(int empid) 
  {
    this.empid = empid;
  }
  public String getEmpname() 
  {
    return empname;
  }
  public void setEmpname(String empname) 
  {
    this.empname = empname;
  }
  public double getEmpsalary() 
  {
    return empsalary;
  }
  public void setEmpsalary(double empsalary) 
  {
    this.empsalary = empsalary;
  }
  public long getEmpmobile() 
  {
    return empmobile;
  }
  public void setEmpmobile(long empmobile) 
  {
    this.empmobile = empmobile;
  }
}

1. Adding hbm.xml file

Before going further, copy one hbm.xml file from anywhere (say, first Student program) into src folder and rename it as Employee.hbm.xml. Remember, this file should be placed in src folder. The package snrao is a subfolder of src.

2. Adding Hibernate libraries

Right click on the project –> MyEclipse –> Add Hibernate Capabilities

You will see the following screen.

hbm2ddl HibernateSessionFactory

Select the radio button Hibernate 3.2 (keep all the selected by default as it is) and click "Next" button. You see the following screen.

hbm2ddl HibernateSessionFactory

Keep the default settings as it is and click over "Browse" button and select snrao package to place the Hibernate.cfg.xml file. You get the next screen.

3. Creating Hibernate.cfg.xml file

hbm2ddl HibernateSessionFactory

Browse the DB Driver and select OIV (OIV is the name of the database connection. Actually a new connection OIV is not required and its place you can use the first program connection SNRaoConnection) to connect to the database. Click "Next" Button.

4. Creating HibernateSessionFactory interface

In the first program – Student, HibernateSessionFactory interface was created manually in the client program. Let us create it through the wizard.

hbm2ddl HibernateSessionFactory

Browse for snrao package by clicking the button "Browse" of Java Package option.

Click "Finish" button. You get the next screen.

5. Adding show_sql and hbm2ddl.auto in cfg.xml file

hbm2ddl HibernateSessionFactory

On the right side there are two options Properties and Mappings with text areas.

a) Properties

Click over "Add" button of Properties option.

hbm2ddl HibernateSessionFactory

Select show_sql from the dropdown list of Property option. In the Value text field write true and say "OK". Again repeat for hbm2ddl.auto and write the value as update.

b) Mappings

Select Mappings option.

Click "add" button and select the Employee.hbm.xml file.

Now altogether three tags are added to cfg file – two from Properties and one from Mapping.

Following is the Hibernate.cfg.xml file generated.









	org.hibernate.dialect.Oracle9Dialect
	jdbc:oracle:thin:@localhost:1521:orcl
	scott
	tiger
        oracle.jdbc.driver.OracleDriver
	OIV
	true
	update

	


Following is the Properties file: Employee.hbm.xml. This is not generated but handwritten.




	

	
	   
	     
	   
	   
	   
	   
	

Observe, the table name and columns names are missing in the <id> and <property> tags. They are given by Hibernate while creating the table. But, it is necessary to write all the field names.

Now write the client program in the snrao package and run.

Following is the Client program: EmployeeClient.java

package snrao;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class EmployeeClient  {

  /**  
    * @param args
  */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session s = HibernateSessionFactory.getSession();
				              // getSession() is a method of HibernateSessionFactory
    Transaction tx = s.beginTransaction();    // observe the code of HSF next
    try
    {
      Employee emp1 = new Employee();
      emp1.setEmpname("S N Rao");
      emp1.setEmpsalary(1222.45);
      emp1.setEmpmobile(999999999);
      s.save(emp1);
      s.flush();
      tx.commit();
      System.out.println("Record inserted");
    }
    catch(Exception e)
    {
      tx.rollback();
    }
  }
}

HibernateSessionFactory is obtained by default, as you have created it in 4th step). This avoids creation of Configuration object and manual loading of hibernate.cfg.xml file (in the first program, Student, you did these manually).

Observe a new table, Employee (on the name of the bean) is created in the database and record inserted.

hbm2ddl HibernateSessionFactory

Observe, the columns are not aligned properly as it looks. It is because the Java string is converted to varchar2(255) and float to 126 digits. The columns are spread a long way. This can be arrested by giving length="10" attribute in the mapping file as follows.



This we will see later.

Following is the directory structure of Second Program – Employee in the Package Explorer.

hbm2ddl HibernateSessionFactory

Following is the source code of HibernateSessionFactory class which is implicitly generated.  This is given for extra reading to know what methods exist and their return types.  You can use these methods in the client program when required.  This is for extra information only.
package snrao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {
    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/snrao/hibernate.cfg.xml";
	private static final ThreadLocal threadLocal = new ThreadLocal();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
            	configuration.configure(configFile);
		sessionFactory = configuration.buildSessionFactory();
	} 
            catch (Exception e) {
		System.err.println("%%%% Error Creating SessionFactory %%%%");
		e.printStackTrace();
	}
    }
    private HibernateSessionFactory() {
    }
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the SessionFactory if needed.
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}
        return session;
    }  	/**   *  Rebuild hibernate session factory  *   */
      public static void rebuildSessionFactory() {
	try {
		configuration.configure(configFile);
		sessionFactory = configuration.buildSessionFactory();
	} catch (Exception e) {
		System.err.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}    /**
     *  Close the single hibernate session instance.
    *  @throws HibernateException  */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
            session.close();
        }
    }  /**   *  return session factory   *   */
public static org.hibernate.SessionFactory getSessionFactory() {  return sessionFactory;  } 
 /**  *  return session factory
     *	session factory will be rebuilded in the next call   */
     public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;  }       /**   *  return hibernate configuration  */
      public static Configuration getConfiguration()   {  return configuration;   }  }

5 thoughts on “hbm2ddl HibernateSessionFactory Hibernate”

Leave a Comment

Your email address will not be published.