Thursday, 27 December 2012

Difference between Hibernate createCriteria, createQuery, createSQLQuery

To create query in the Hibernate ORM framework, there is three different types. The following are the three ways to create query instance:

  1. session.createQuery()
  2. session.createSQLQuery()
  3. session.createCriteria()

session.createQuery()
The method createQuery() creates Query object using the HQL syntax.
Query query = session.createQuery("from Student s where s.name like 'k%'");

session.createSQLQuery()
The method createSQLQuery() creates Query object using the native SQL syntax.
Query query = session.createQuery("Select * from Student");

session.createCriteria()
The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand.
Criteria criteria = session.createCriteria(Student.class);

Wednesday, 26 December 2012

LazyInitializationException: could not initialize proxy - no Session

Understand The Problem

If you access detached objects that have been loaded in the Session inside your JSP (or any other view rendering mechanism), you might hit an unloaded collection or a proxy that isn't initialized. The exception you get is: LazyInitializationException: Session has been closed (or a very similar message). Of course, this is to be expected, after all you already ended your unit of work.

A LazyInitializationException will be thrown by Hibernate if an uninitialized collection or proxy is accessed outside of the scope of the Session, i.e., when the entity owning the collection or having the reference to the proxy is in the detached state.

Solution One
Hibernate.initialize()
Hibernate.isInitialized()

The static methods Hibernate.initialize() and Hibernate.isInitialized(), provide the application with a convenient way of working with lazily initialized collections or proxies. Hibernate.initialize(cat) will force the initialization of a proxy, cat, as long as its Session is still open. Hibernate.initialize( cat.getKittens() ) has a similar effect for the collection of kittens.

Solution Two
Another option is to keep the Session open until all required collections and proxies have been loaded.

In some application architectures, particularly where the code that accesses data using Hibernate, and the code that uses it are in different application layers or different physical processes, it can be a problem to ensure that the Session is open when a collection is initialized.

There are two basic ways to deal with this issue:
  • In a web-based application, a servlet filter can be used to close the Session only at the end of a user request, once the rendering of the view is complete (the Open Session in View pattern).
  • In an application with a separate business tier, the business logic must "prepare" all collections that the web tier needs before returning. This means that the business tier should load all the data and return all the data already initialized to the presentation/web tier that is required for a particular use case. Usually, the application calls Hibernate.initialize() for each collection that will be needed in the web tier (this call must occur before the session is closed) or retrieves the collection eagerly using a Hibernate query with a FETCH clause or a FetchMode.JOIN in Criteria. This is usually easier if you adopt the Command pattern instead of a Session Facade.
  • You can also attach a previously loaded object to a new Session with merge() or lock() before accessing uninitialized collections or other proxies. Hibernate does not, and certainly should not, do this automatically since it would introduce impromptu transaction semantics.













http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html#performance-fetching-initialization

Tuesday, 18 December 2012

Transactional patterns (and anti-patterns)

1. Session-per-operation anti-pattern
2. Session-per-request pattern
3. Conversations
4. Session-per-application


1. Session-per-operation anti-pattern

This is an anti-pattern of opening and closing a Session for each database call in a single thread.

2. Session-per-request pattern

This is the most common transaction pattern.The term request here relates to the concept of a system that reacts to a series of requests from a client/user.
At the beginning of handling such a request, the application opens a Hibernate Session, starts a transaction, performs all data related work, ends the transaction and closes the Session.
Within this pattern there is a common technique of defining a current session to simplify the need of passing this Session around to all the application components that may need access to it.
 Hibernate provides support for this technique through the getCurrentSession method of the SessionFactory.
The concept of a "current" session has to have a scope that defines the bounds in which the notion of "current" is valid. This is purpose of the org.hibernate.context.spi.CurrentSessionContext contract. There are 2 reliable defining scopes:

  • First is a JTA transaction because it allows a callback hook to know when it is ending which gives Hibernate a chance to close the Session and clean up.Using this implementation, a Session will be opened the first time getCurrentSession is called within that transaction.
  • Secondly is this application request cycle itself.Here an external component is responsible for managing the lifecycle and scoping of a "current" session. At the start of such a scope, ManagedSessionContext's bind method is called passing in the Session. At the end, its unbind method is called. Some common examples of such "external components" include:
    • javax.servlet.Filter implementation
    • AOP interceptor with a pointcut on the service methods
    • A proxy/interception container

The getCurrentSession() method has one downside in a JTA environment. If you use it, after_statement connection release mode is also used by default. Due to a limitation of the JTA specification, Hibernate cannot automatically clean up any unclosed ScrollableResults or Iterator instances returned by scroll() or iterate(). Release the underlying database cursor by calling ScrollableResults.close() or Hibernate.close(Iterator) explicitly from a finally block.

3. Conversations

The session-per-request pattern is not the only valid way of designing units of work. Many business processes require a whole series of interactions with the user that are interleaved with database accesses. In web and enterprise applications, it is not acceptable for a database transaction to span a user interaction.
Even though we have multiple databases access here, from the point of view of the user, this series of steps represents a single unit of work. There are many ways to implement this in your application.

A first naive implementation might keep the Session and database transaction open while the user is editing, using database-level locks to prevent other users from modifying the same data and to guarantee isolation and atomicity. This is an anti-pattern, because lock contention is a bottleneck which will prevent scalability in the future.

4. Session-per-application

Discussion coming soon..

http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html/ch02.html#session-per-request

Wednesday, 5 December 2012

Difference between First Order and Second Order sql injection Attack

First Order Attack

The attacker can simply enter a malicious string and cause the modified code to be executed immediately.

Second Order Attack

The attacker injects into persistent storage (such as a table row) which is deemed as a trusted source. An attack is subsequently executed by another activity.

A second order SQl injection succeeds primarily because the application developeer assumes that the data can be trusted by default when it comes from what he thinks is a reliable source.
In this demonstration, and audit trigger tracks table creations. Because of a SQL injection vulnerability in the trigger, and attacker is able to create a table with malicious string embedded in the table name.


Lateral Injection

The attacker can manipulate the implicit function To_Char() by changing the values of the environment variables, NLS_Date_Format or NLS_Numeric_Characters.

http://download.oracle.com/oll/tutorials/SQLInjection/html/lesson1/les01_tm_attacks.htm

Tuesday, 4 December 2012

Difference between Session.openSession() & Session.getCurrentSession()


  1. What should be the value for hibernate.current_session_context_class?
  2. Session s = HibernateUtil.getSessionFactory().openSession();
    Session s = HibernateUtil.getSessionFactory().getCurrentSession()
Which one is better "one session per web app" or "one session per request"?

hibernate.current_session_context_class to thread and then implement something like a servlet filter that opens the session - then you can access that session anywhere else by using the SessionFactory.getCurrentSession().

SessionFactory.openSession() always opens a new session that you have to close once you are done with the operations. SessionFactory.getCurrentSession() returns a session bound to a context - you don't need to close this.

You should never use "one session per web app" - session is not a thread safe object - cannot be shared by multiple threads. You should always use "one session per request" or "one session per transaction"

GetSession gives you a Hibernate session, and associates that session with the current thread. Then, if you call getSession again, you get the session that was originally created. This is good.

Some people don't like binding the Hibernate Session to the current thread, and they don't like the ease of getting the current Session back with getSession. Instead, these people use openSession, which creates a new Session and asks the DEVELOPER to manage where the session goes. I gues you could put it in a list or a cache, or whatever, but YOU must manage it, as though you were creating your own database connection pool or something.

getSession is usually sufficient. openSession provides and facilitates a greater level of management of where the session is stored and managed. It's certainly an advanced option, but one that does indeed fit the need of very clever developers who are doing some nifty things with the session.

Some people who are much better looking than me, not to mention being much more intelligent, discussed just this topic in the following JavaRanch thread:

Monday, 3 December 2012

The use of Data Structures in Java -- ArrayLists

package com.gea.boe.bean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class BoeMain
{
    public static void main(String[] args)
    {
        ArrayList<String> myList = new ArrayList<String>();
        myList.add("item1");
        myList.add("item2");
        myList.add("item3");
        myList.add("item4");
        // Display
        display(myList);
        // Remove
        addAndRemoveFromArrayList(myList, 1, "REMOVE");
        // Display
        display(myList);
        // Add
        addAndRemoveFromArrayList(myList, 1, "ADD");
        // Display
        display(myList);
        // Sorting
        sortingArrayList(myList);
        // Display
        display(myList);
        //Searching
        searchingFromArrayList(myList,"item4");
       
    }
    // Remove items from Array List
    public static void addAndRemoveFromArrayList(ArrayList<String> arrayList, int indexOfItemToRemove, String addRemove)
    {
        if ("ADD".equalsIgnoreCase(addRemove))
        {
            String addItem = "item9";
            arrayList.add(indexOfItemToRemove, addItem);
        }
        else if ("REMOVE".equalsIgnoreCase(addRemove))
        {
            arrayList.remove(indexOfItemToRemove);
        }
    }
    // Here is the list, output methods
    public static void display(ArrayList<String> arrayList)
    {
        System.out.println("There are (" + arrayList.size() + ") items in the list.");
        // output method 1
        for (int i = 0; i < arrayList.size(); i++)
        {
            System.out.println(i + " -->> " + arrayList.get(i));
        }
        // output method 2
        for (Iterator<String> iter = arrayList.iterator(); iter.hasNext();)
        {
            System.out.println("-->> " + iter.next());
        }
        // output method 3
        System.out.println(arrayList);
    }
    // Sorting Array List
    public static void sortingArrayList(ArrayList<String> arrayList)
    {
        Collections.sort(arrayList);
    }
    //Searching
    public static void searchingFromArrayList(ArrayList<String> arrayList,String searchItem)
    {
        boolean searchResult = arrayList.contains(searchItem);
       
        if(searchResult == true)
            System.out.println("Item found at position " + arrayList.indexOf(searchItem));
        else
            System.out.println("Item NOT found");
    }
}