Thursday, May 30, 2013

Hibernate: Building SessionFactory

In almost all applications, SessionFactory should be instantiated once during application initialization. This single instance should be used to create any session object in application.
SessionFactoty is thread safe and can be shared.

Ways to configureSessionFactory:

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

1.       When new Configuration() is called, Hibernate searches for a file named hibernate.properties in the classpath. If it’s found, all hibernate.* properties are loaded to the Configuration object.
2.       When configure() is called, Hibernate searches for a file named hibernate.cfg.xml in the class path, and exception is thrown if it is not found.
If settings in the XML configuration file and properties file are same (duplicate) then XML settings override the previous ones.
3.       If you wish to use a different file than hibernate.cfg.xml or to have Hibernate look in a subdirectory of your classpath for the XML configuration file, you must pass file name with complete path w.r.t. classpath as an argument of the configure() method.
SessionFactory sessionFactory
= new Configuration().configure("/config/test.cfg.xml").buildSessionFactory();

4.       You can always set additional configuration options or mapping file locations on the Configuration object programmatically, before building the SessionFactory object.
SessionFactory sessionFactory
= new Configuration().configure("/config/test.cfg.xml").setProperty().buildSessionFactory();



Example Code: HibernateUtil.java

package com.test.util;

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


public class HibernateUtil {
    
    private static SessionFactory sessionFactory;
    
    static{
        try {
            sessionFactory = new Configuration().configure("com/test/resources/hibernate.cfg.xml").buildSessionFactory();
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    
    public static SessionFactory getSessionFactory(){
            return sessionFactory;
    }
    
    public static void shutDown(){
    getSessionFactory().close();
    }
    
}

Friday, April 26, 2013

Java: Initializing Class and objects of Class - Order of execution of different code blocks

A Java class contains instance variables, static class level variables, static initialization block, instance initialization block, constructor, static methods, instance methods.

Order of execution:
1. Class level attributes (static variables) are initialized to value which is specified (explicit value) or to default value if no explicit value given and static initialization block are called as per their order (top to down) in java class. If we try to access field before it is declared in class initialization block, it gives Illegal forward reference compile time error.

2. Instance fields are initialized to explicit or default value and instance initialization block is called as per their sequence.


Below example class gives more details:



public class TestInit {

//instance variable
String b = "VAL1";

//instance level initialization block
{
System.out.println("instance initialization block I called");
System.out.println("instance level variable 'b' is already initialized to:"+ b );
}

//class level initialization block
static{
System.out.println("static initialization block I called");
}

//Class level field
static int a = 5;

//class level initialization block
static{
System.out.println("static initialization block II called");
System.out.println("class level variable 'a' is already initialized to:"+ a);
}

//instance variable
int c = 10;

//instance level initialization block
{
System.out.println("instance initialization block II called");
System.out.println("instance level variable 'c' is already initialized to:"+ c);
}



/**
* @param args
*/
public static void main(String[] args) {
TestInit t = new TestInit();

}

}

Output after running above class:


static initialization block I called
static initialization block II called
class level variable 'a' is already initialized to:5
instance initialization block I called
instance level variable 'b' is already initialized to:VAL1
instance initialization block II called
instance level variable 'c' is already initialized to:10




Saturday, April 20, 2013

Threadlocal cache in web application

Application server maintains thread pool which is used to allocate thread to process client requests.
When you want to or plan to use thread local cache in web application, take care of clearing cache before request processing is complete. Because if by mistake your thread local cache data is not cleared from cache, when that thread processes next request, cached data is still there. If actual data is changed in between the two request, you will still get old data from cache. It becomes very difficult to find out root cause of problems which occurs due to wrong implementation of threadlocal cache in web applications. So always take care whenever you decide to use threadlocal cache in web applications to improve performance. Your comments are most welcome.