Tuesday, December 25, 2012

ServletContext

How to get the ServletContext in Struts 2

1) ServletActionContext - Get the ServletContext object directly from org.apache.struts2.ServletActionContext.

import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
 
public class CustomerAction extends ActionSupport{
 
 public String execute() throws Exception { 
  ServletContext context = ServletActionContext.getServletContext(); 
  return SUCCESS; 
 } 
}


2) ServletContextAware - implements the org.apache.struts2.util.ServletContextAware interface.

When Struts 2 ‘servlet-config’ interceptor is seeing that an Action class is implemented the ServletContextAware interface, it will pass a ServletContext reference to the requested Action class via the setServletContext() method.

import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
 
public class CustomerAction 
    extends ActionSupport implements ServletContextAware{
  ServletContext context;
 
 public String execute() throws Exception {
  return SUCCESS;
 }
 
 public void setServletContext(ServletContext context) {
  this.context = context;
 }
}

Saturday, December 8, 2012

Enum

Enum represent a fixed set of constants
Eg: Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
A data sets where you know all possible values at compile time
public enum Directions {
     NORTH, SOUTH, EAST, WEST 
}

How to represent enumerable value without Java enum
Since Enum in Java is only available from Java 1.5 its worth to discuss how we used to represent enumerable values in Java prior JDK 1.5 and without it. I use public static final constant to replicate enum like behavior. Let’s see an Enum example in Java to understand the concept better. In this example we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).
class CurrencyDenom {
            public static final int PENNY = 1;
            public static final int NICKLE = 5;
            public static final int DIME = 10;
            public static final int QUARTER = 25;

      }

class Currency {
   int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                 // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

Though this can server our purpose it has some serious limitations:
1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Java Enum is answer of all this limitation. Enum in Java is type-safe, provides meaningful String names and has there own namespace. Now let's see same example using Enum in Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};


Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum are type like class and interface in Java. Also we have followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.

What is Enum in Java

Enum is a keyword in java and on more detail term Java Enum is type like class and interface and can be used to define a set of Enum constants. Enum constants are implicitly static and final and you can not change there value once created. Enum in Java provides type-safety and can be used inside switch statment like int variables. Since enum is a keyword you can not use as variable name and since its only introduced in JDK 1.5 all your previous code which has enum as variable name will not work and needs to be re-factored.

Benefits of Enums in Java:

1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is compiler error to assign something else unlike the public static final variables used in Enum int pattern and Enum String pattern.

2) Enum has its own name-space.

3) Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.

Important points about Enum in Java
1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.

public enum Currency {PENNY, NICKLE, DIME, QUARTER}; Currency coin = Currency.PENNY; coin = 1; //compilation error

2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.

3) You can specify values of enum constants at the creation time as shown in below example: public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)}; But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
  
public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

        private Currency(int value) {
                this.value = value;
        }
};  

Constructor of enum in java must be private any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.

4) Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:

Currency.PENNY = Currency.DIME; The final field EnumExamples.Currency.PENNY cannot be re assigned.

5) Enum in java can be used as an argument on switch statment and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement:
   Currency usCoin = Currency.DIME;
    switch (usCoin) {
            case PENNY:
                    System.out.println("Penny coin");
                    break;
            case NICKLE:
                    System.out.println("Nickle coin");
                    break;
            case DIME:
                    System.out.println("Dime coin");
                    break;
            case QUARTER:
                    System.out.println("Quarter coin");
    }

from JDK 7 onwards you can also String in Switch case in Java code.

6) Since constants defined inside Enum in Java are final you can safely compare them using "==" equality operator as shown in following example of Java Enum:
Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
  System.out.println("enum in java can be compared using ==");
}

By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.

7) Java compiler automatically generates static values() method for every enum in java. Values() method returns array of Enum constants in the same order they have listed in Enum and you can use values() to iterate over values of Enum in Java as shown in below example:
for(Currency coin: Currency.values()){
        System.out.println("coin: " + coin);
}

And it will print: coin: PENNY coin: NICKLE coin: DIME coin: QUARTER

Notice the order its exactly same with defined order in enums.

8) In Java Enum can override methods also. Let’s see an example of overriding toString() method inside Enum in Java to provide meaningful description for enums constants.
public enum Currency {
  ........
      
  @Override
  public String toString() {
       switch (this) {
         case PENNY:
              System.out.println("Penny: " + value);
              break;
         case NICKLE:
              System.out.println("Nickle: " + value);
              break;
         case DIME:
              System.out.println("Dime: " + value);
              break;
         case QUARTER:
              System.out.println("Quarter: " + value);
        }
  return super.toString();
 }
};        

And here is how it looks like when displayed: Currency usCoin = Currency.DIME; System.out.println(usCoin);

output: Dime: 10

9) Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum. These classes are high performance implementation of Map and Set interface in Java and we should use this whenever there is any opportunity.

10) You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.

11) Instance of Enum in Java is created when any Enum constants are first called or referenced in code.

12) Enum in Java can implement the interface and override any method like normal class It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface. Let's see and example of how to implement interface using Java Enum:
public enum Currency implements Runnable{
  PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
  private int value;
  ............
        
  @Override
  public void run() {
  System.out.println("Enum in Java implement interfaces");
                
   }
}

13) You can define abstract methods inside Enum in Java and can also provide different implementation for different instances of enum in java. Let’s see an example of using abstract method inside enum in java
public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();
        
          private Currency(int value) {
                  this.value = value;
          }
          ..............
  }      

In this example since every coin will have different color we made the color() method abstract and let each instance of Enum to define there own color. You can get color of any coin by just calling color() method as shown in below example of java enum:

System.out.println("Color: " + Currency.DIME.color());
Ref: javarevisited

Monday, November 26, 2012

Struts2 Interceptors


Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.



lifecycle of Struts2 framework

- Request is generated by user and sent to Servlet container.
- Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.
- One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
- Action is executed and the Result is generated by Action.
- The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.

Thus the Struts2 Interceptors removes cross cutting tasks such as logging from action components and create cleaner separation of MVC.

Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file. We can create our own custom Interceptors and plugin into a Struts2 based web application.

Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action. Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work. Interceptors can alter the workflow of action. It may prevent the execution of action

Reference:viralpatel

Wednesday, November 21, 2012

Abstract classes vs. interfaces

In Java, under what circumstances would you use abstract classes instead of interfaces? When you declare a method as abstract, can other nonabstract methods access it? In general, could you explain what abstract classes are and when you might use them?
Those are all excellent questions: the kind that everyone should ask as they begin to dig deeper into the Java language and object-oriented programming in general Yes, other nonabstract methods can access a method that you declare as abstract. But first, let's look at when to use normal class definitions and when to use interfaces.Then I'll tackle abstract classes.
Class vs. Interface
Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI.Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm.All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object.If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, Media Strategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
Interface vs. abstract class
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies.They're also a good choice for nonleaf classes in class hierarchies.
Reference: JavaWorld

Tuesday, October 16, 2012

Serialization Vs Externalizable

Serializable is a marker interface and doesn't contain any methods whereas Externalizable interface contains two methods: writeExternal(ObjectOutput) and readExternal(ObjectInput). But, the main difference between the two is that Externalizable interface provides complete control to the class implementing the interface over the object serialization process whereas Serializable interface normally uses default implementation to handle the object serialization process.

While implementing
Serializable, you are not forced to define any method as it's a marker interface. However, you can use the writeObject or readObject methods to handle the serilaization process of complex objects. But, while implementing Externalizable interface, you are bound to define the two methods: writeExternal and readExternal and all the object serialization process is solely handled by these two methods only.

In case of
Serializable interface implementation, state of Superclasses are automatically taken care by the default implementation whereas in case of Externalizable interface the implementing class needs to handle everything on its own as there is no default implementation in this case.

when to use what?

If everything is automatically taken care by implementing the
Serializable interface, why would anyone like to implement the Externalizable interface and bother to define the two methods? Simply to have the complete control on the process. OKay... let's take a sample example to understand this. Suppose we have an object having hundreds of fields (non-transient) and we want only few fields to be stored on the persistent storage and not all. One solution would be to declare all other fields (except those which we want to serialize) as transient and the default Serialization process will automatically take care of that. But, what if those few fields are not fixed at design tiime instead they are conditionally decided at runtime. In such a situation, implementing Externalizable interface will probably be a better solution. Similarly, there may be scenarios where we simply don't want to maintain the state of the Superclasses (which are automatically maintained by the Serializable interface implementation).

Which has better performance - Externalizable or Serializale?

In most of the cases (or in all if implemented correctly), Externalizable would be more efficient than Serializable for the simple reason that in case of Externalizable the entire process of marshalling, un-marshalling, writing to the stream, and reading back from stream, etc. is
under your control i.e., you got to write the code and you can of course choose the best way depending upon the situaton you are in. In case of Serializable, this all (or at least most of it) is done implicitly and the internal implementation being generic to support any possible case, can ofcourse not be the most efficient. The other reason for Serializable to be less efficient is that in this case several reflective calls are made internally to get the metadata of the class. Of course, you would not need any such call is needed in case Externalizable.

However, the efficiency comes at a price. You
lose flexibility because as soon as your class definition changes, you would probably need to modify your Externaliable implementation as well. Additionally, since you got to write more code in case Externalizable, you increase the chances of adding more bugs in your application.

Another disadvantage of Externalizable is that you got to have the class to interpret the stream as the stream format is an opaque binary data. Normal Serialization adds field names and types (this why reflective calls are needed here) into the stream, so it's possible to re-construct the object even without the availability of the object's class. But, you need to write the
object reconstruction code yourself as Java Serialization doesn't provide any such API at the moment. The point is that in case of Serialzable you can at least write your code as the stream is enriched with field names and types whereas in case Externalizable the stream contains just the data and hence you can't unless you use the class definition. As you can see Serializable not only makes many reflective calls, but also puts the name/type info into the stream and this would of course take some time making Serialzable slower than the corresponding Externalizable process where you got to stuff only the data into the stream.

Struts 2 Flow

  • When a client request is given, a web container will receive request
  • Web container loads web.xml and verifies whether the url-patterns are verified or not, if matches web-container transfer the request to FilterDispatcher
  • FilterDispatcher hand overs the request to ActionProxy, it is a proxy class which is responsible to apply before and after services to original business logic
  • ActionProxy contacts ConfiguraionManager class, to know the suitable Action for the request and the needed services for the request
  • ConfigurationManager class loads structs.xml and provides the required information back to ActionProxy
  • ActionPorxy delegates the request along with its information to ActionInvocation
  • ActionInvocation executes the interceptors added to an Action from 1 – N, after that it will calls the business logic implemented from N – 1 in reverse order
  • ActionInvocation receives finally result produced by an action aclass
  • ActionProxy transfers the result back to FilterDispatcher
  • FilterDispatcher selects an appropriate view, basing on the result
  • Finally FilterDispatcher uses RequestDispatchers forwarding mechanism and forward a view as a response back to the client

Tuesday, October 9, 2012

Life cycle of Servlet

The life cycle of a servlet can be categorized into four parts:
  1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
  2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

    The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
  3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
  4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet  releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection. 
Referance: roseindia

Monday, October 8, 2012

Exception

What is Exception ?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

In java it is possible to define two categories of Exceptions and Errors.
  • JVM Exceptions: These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException...
  • Programmatic exceptions: These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalState...
What is difference between Error and Exception?  
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

What is difference between ClassNotFoundException and NoClassDefFoundError?
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. 
Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass 
does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the Class Loader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the Class Loader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.
 

Basic java interview Questions

Can you declare a class as ‘private’ ?
No, if we declare a class as private , then it is not available to java compiler and hence a compile time error occurs, But inner classes can be declared as private.

What is the difference between instance variables and class variables(static variables) ?
1. An Instance variable is a variable whose separate copy is availabe to each object. A class variable is a variable whose single copy in memory is shared by all objects.
2. Instance variables are created in the objects on heap memory. Class variables are stored on method area.

Why instance Variables are not available to static methods ?
After executing static methods, JVM creates the objects. So the instance variables of the objects are not available to static methods.

Is it possible to compile and run a Java program without writing main( ) method ?
Yes , it is possible by using a static block in the Java program.

What is anonymous inner class ?
It is an inner class whose name is not written in the outer class and for which only one object is created.

What is method signature ?
Method signature represents the method name along with method parameters.

JSP Life Cycle

A JSP life cycle is similar to Servlet life cycle.JSP life cycle can be defined as the entire process from its creation till the destruction.

Four things is happen when we send a request for JSP are as follows:
1) Compilation
2) Initialization
3) Execution
4) Destroy - Cleanup

-->
The three major phases of JSP life cycle are very similar to Servlet Life Cycle
1) jspInit()
2)  _jspService()
3) jspDestroy()
-->

(1) JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
  1. Parsing the JSP.
  2. Turning the JSP into a servlet.
  3. Compiling the servlet.

(2) JSP Initialization:

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit(){
  // Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

(3) JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
   // Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods i.e. GET, POST, DELETE etc.

(4) JSP Cleanup:

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
   // Your cleanup code goes here.
}

Friday, October 5, 2012

Interface

What is an interface ?
An interface is a specification of method prototypes, All the methods of the interface are public and abstract.


Why the methods of interface are public and abstract by default ?
Interface methods are public since they should be available to third party vendors to provide implementation. They are abstract because their implementation is left for third party vendors.


Can you implement one interface from another ?
No, we can’t implementing an interface means writing body for the methods. This can not be done again in an interface, since none of the methods of the interface can have body.

Can you write a class within an interface ?
Yes, it is possible to write a class within an interface.




What do you call the interface without any members ?

An interface without any members is called marking interface or tagging interface. It marks the class objects for a special purpose. For example, Clonable(java.lang) and Serializable(java.io) are two marking interfaces. Clonable interface indicates that a particular class objects are cloneable while Serializable interface indicates that a particular class objects are serializable.

What is abstraction ?

Hiding the unnecessary data from the user and expose only needed data is of interest to the user.
A good example for abstraction is a car. Any car will have some parts like engine, radiator, mechanical and electrical equipment etc. The user of the ca r (driver) should know how to drive the car and does not require any knowledge of these parts. For example driver is never bothered about how the engine is designed and the internal parts of the engine. This is why, the car manufacturers hide these parts from the driver in a separate panel, generally at the front.

Overloading and Overriding

What is method overloading ?
Writing two or more methods in the same class in such a way that each method has same name but with different method signatures – is called method overloading.
What is method overriding ?
Writing two or more methods in super and sub classes such that the methods have same name and same signature is called method overriding.


Method Overloading
Writing two or more methods with the same name but with different signatures is called method overloading.
Method overloading is done in the same class.
In method overloading, method return type can be same or different.
JVM decides which method is called depending on the difference in the method signatures.
Method overloading is done when the programmer wants to extend the already available features.
Method overloading is code refinement. Same method is refined to perform a different task.

Method Overriding
Writing two or more methods with the same name and same signatures is called method overriding.
Method overriding is done in super and sub classes.
In method overriding method return type should also be same.
JVM decides which method is called depending on the data type (class) of the object used to call the method.
Method overriding is done when the programmer wants to provide a different implementation(body) for the same feature.
Method overriding is code replacement. The sub class method overrides(replaces) the super class method.

What is the difference between dynamic polymorphism and static polymorphism ?

Dynamic polymorphism is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.

Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows which method is called. Method overloading and method overriding using static methods; method overriding using private or final methods are examples for static polymorphism.

Wednesday, October 3, 2012

Native Queries with Hibernate Annotations

Hibernate EntityManager implements the programming interfaces and lifecycle rules as defined by the EJB3 persistence specification. Together with Hibernate Annotations, this wrapper implements a complete (and standalone) EJB3 persistence solution on top of the mature Hibernate core. In this post I will describe how map native queries (plain SQL) using Hibernate Annotations. Hibernate Annotations supports the use of Native queries through the @NamedNativeQuery and the @SqlResultSetMapping annotations.
  • @NamedNativeQuery: Specifies a native SQL named query.
  • @SqlResultSetMapping: Used to specify the mapping of the result of a native SQL query.
You will not need any EJB container support. At a minimum, you will need Hibernate core and Hibernate Annotations. The entire list of required Jar files is provided at the end.
  1. The Hibernate Configuration File: Nothing new here. Except that there are no mappings defined. I used programmatic declaration of mapping for this example as shown in the following steps.
    <!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
     <session-factory>
      <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
      <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
      <property name="connection.username">scott</property>
      <property name="connection.password">tiger</property>
      <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
      <property name="hibernate.current_session_context_class">thread</property>
     </session-factory>
    </hibernate-configuration>
    hibernate.cfg.xml
  2. The Entity class:
    package data;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EntityResult;
    import javax.persistence.FieldResult;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQuery;
    import javax.persistence.SqlResultSetMapping;
    
    @Entity
    @SqlResultSetMapping(name = "implicit",
     entities = @EntityResult(entityClass = data.Employee.class))
    @NamedNativeQuery(name = "implicitSample",
     query = "select e.empno empNumber, e.ename empName, e.job empJob,
     e.sal empSalary, salg.grade empGrade from emp e, salgrade salg 
    where e.sal between salg.losal and salg.HISAL", resultSetMapping = "implicit")
    
    //@SqlResultSetMapping(name = "explicit", 
    entities = { @EntityResult(entityClass = data.Employee.class, fields = { 
    //    @FieldResult(name = "empNumber", column = "empno"), 
    //    @FieldResult(name = "empName", column = "ename"),
    //    @FieldResult(name = "empJob", column = "job"), 
    //    @FieldResult(name = "empSalary", column = "sal"), 
    //    @FieldResult(name = "empGrade", column = "grade") }) })
    //@NamedNativeQuery(name = "implicitSample", 
    //    query = "select e.empno empno, e.ename ename, e.job job, e.sal sal, salg.grade grade
     from emp e,
     salgrade salg where e.sal between salg.losal and salg.HISAL", 
    resultSetMapping = "explicit")
    public class Employee {
    
     private String empNumber;
    
     private String empName;
    
     private String empJob;
    
     private Double empSalary;
    
     private int empGrade;
    
     @Column
     @Id
     public int getEmpGrade() {
       return empGrade;
     }
    
     public void setEmpGrade(int empGrade) {
       this.empGrade = empGrade;
     }
    
     @Column
     public String getEmpJob() {
       return empJob;
     }
    
     public void setEmpJob(String empJob) {
       this.empJob = empJob;
     }
    
     @Column
     public String getEmpName() {
       return empName;
     }
    
     public void setEmpName(String empName) {
       this.empName = empName;
     }
    
     @Column
     public String getEmpNumber() {
       return empNumber;
     }
    
     public void setEmpNumber(String empNumber) {
       this.empNumber = empNumber;
     }
    
     @Column
     public Double getEmpSalary() {
       return empSalary;
     }
    
     public void setEmpSalary(Double empSalary) {
       this.empSalary = empSalary;
     }
    
    }
    Employee.java
    • The implitic mapping (the uncommented @NamedNativeQuery and @SqlResultSetMapping declarations are used for implicitly mapping the ResultSet to the entity class. Note that the SQL column names match the field names in the class. If the names do not match then you can set the name attribute of the @Column annotation to the column name in the query.
    • The commented @NamedNativeQuery and the @SqlResultSetMapping declarations explicitly map the fields to the columns. This will come in handy when using joins and composite keys etc.
    • Note the package definitions refer to javax.persistence and not the hibernate packages. If the packages are not declared properly, you will most likely end up with some exceptions like the following
      org.hibernate.hql.ast.QuerySyntaxException: Employee is not mapped.
      While there are other causes for this exception, the package declarations did cause a little trouble for me.
  3. The Client:
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.cfg.Configuration;
    
    import data.Employee;
    
    public class Client {
    
     public static void main(String[] args) {
       Configuration config = new AnnotationConfiguration()
    .addAnnotatedClass(Employee.class).configure();
    
       SessionFactory sessionFactory = config.buildSessionFactory();
       Session session = sessionFactory.getCurrentSession();
    
       List result = null;
       try {
         session.beginTransaction();
    
         result = session.getNamedQuery("implicitSample").list();
         System.out.println("Result size : " + result.size());
         session.getTransaction().commit();
       } catch (Exception e) {
         e.printStackTrace();
       }
       System.out.println(result.size());
     }
    
    }

  4. Jar Files: The following jar files need to be included in the classpath
    hibernate3.jar
    commons-collections-2.1.1.jar
    antlr-2.7.6.jar
    commons-logging-1.0.4.jar
    hibernate-annotations.jar
    ejb3-persistence.jar
    hibernate-commons-annotations.jar
    dom4j-1.6.1.jar
    ojdbc14.jar
    jta.jar
    log4j-1.2.11.jar
    xerces-2.6.2.jar
    xml-apis.jar
    cglib-2.1.3.jar
    asm.jar
     
    Reference: java-x.blogspot.in 

Saturday, September 29, 2012

Comparator Example


When will you use Comparator and Comparable interfaces?
-java.util.Comparator and java.lang.Comparable
java.util.Comparator compares some other class’s instances, while java.lang.Comparable compares itself with another object.

Comparator vs Comparable in Java

Here are some of the common differences, which is worth remembering to answer this question if asked during a telephonic or face to face interview:

1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package, which very much says that Comparator should be used as an utility to sort objects which Comparable should be provided by default.

2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implements Comparable interface.Its always good practice to override compareTo() for value objects.

5) If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

6)Objects which implement Comparable in Java can be used as keys in a SortedMap like TreeMap or elements in a SortedSet for example TreeSet, without specifying any Comparator.

public class Person implements Comparable {
    private int person_id;
    private String name;
   
    /**
     * Compare current person with specified person
     * return zero if person_id for both person is same
     * return negative if current person_id is less than specified one
     * return positive if specified person_id is greater than specified one
     */
    @Override
    public int compareTo(Object o) {
        Person p = (Person) o;
        return this.person_id - o.person_id ;
    }
    ….
}


/**
 * Comparator implementation which sorts Person objects on person_id field
 */
public class SortByPerson_ID implements Comparator{

    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o;
        Person p2 = (Person) o;
        return p1.getPersonId() - p2.getPersonId();
    }
}


Use Collection.sort to sort custom class and user defined comparator

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;

@SuppressWarnings("rawtypes")
class employee implements Comparable {
    private String name;
    private Double salary;
   
    public employee(String name, Double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public Double getSalary() {
        return salary;
    }

    public String toString(){
        return "Name = "+getName()+", Salary = "+getSalary();
    }

    @Override
    public int compareTo(Object o) {
        if(!(o instanceof employee))
            throw new ClassCastException();
       
        employee e = (employee)o;
        return name.compareTo(e.getName());
    }
   
    static class SalaryComparator implements Comparator {
        @Override
        public int compare(Object o1, Object o2) {
            if(! (o1 instanceof employee) || !(o2 instanceof employee))
                throw new ClassCastException();
           
            employee e1 = (employee) o1;
            employee e2 = (employee) o2;
            return (int) (e1.getSalary() - e2.getSalary());
        }       
    }     
}

public class collectionUtil {

    /**
     * @param args
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        String[] names = { "A", "E", "C", "B", "D" };
        Double[] salaries = { 2.0, 5.0, 6.0, 4.0, 3.0 };
       
        List l = new ArrayList();

        for (int i=0; i < names.length; i++)
            l.add(new employee(names[i], salaries[i]));
       
        Collections.sort(l);
        ListIterator litre = l.listIterator();
        while (litre.hasNext()) {
            //Object object = (//Object) litre.next();
            System.out.println(litre.next());
        }
       
        System.out.println("============================");
       
        Collections.sort(l, new employee.SalaryComparator());
        litre = l.listIterator();
        while (litre.hasNext()) {
            //Object object = (//Object) litre.next();
            System.out.println(litre.next());
        }
       
    }

}

Static Block

If you need to do computation in order to initialize your static variable, you can declare a static block which gets executed exactly once, when the class is first loaded.

Following example shows a class that has static method, some static variable and static initialization,

class useStatic {
  static int a=3;
  static int b;

  static void sMethod(int x){
    System.out.println ("x = "+x);
    System.out.println ("a = "+a);
    System.out.println ("b = "+b);
  }

  static {
     System.out.println (" static block initialized");
     b = a * 4;
  }

  public static void main(String arg[]){
   sMethod(42);
  }

As soon as the useStatic class is loaded, all the static statement are executed. First a is set to 3, then the static block executes (printing a message), and finally b is initalized to a*4 or 12. The main is call,  which calls sMethod() , passing 42 to x so the output is x= 42,a = 3, b = 12.  

the o/p is look's like :

static block initialized
x = 42
a = 3
b = 12

Hope this example helps you to understand static .....

Thursday, September 27, 2012

Hibernate general flow

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML/annotation) configuration files.

Hibernat general flow

Wednesday, September 26, 2012

What is static ?

Static means one per Class, not one for each object.

Static means one per Class, not one for each object no matter how many instance of a class might exist, this means that you can use them without creating an instance of a class. 
Static method are implicitly final, because overriding is done based on the type of a class and are attached to a class, not on object.  static method in a super class can be shadowed by another static method in a sub class, as long as the original method was not declared final. However, you can't override a static method with a non static method. 
In other words, you can't change a static method into an instance method in a class.

What is Static Import?
In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say: double r = Math.cos(Math.PI * theta); or System.out.println("Blah blah blah"); You may want to avoid unnecessary use of static class members like Math. and System. For this use static import. For example above code when changed using static import is changed to:
import static java.lang.System.out;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
...
double r = cos(PI * theta);
out.println("Blah blah blah");
...

So whats the advantage of using above technique? 1) readability of the code. 2) Instead of writing name of static class, directly write the method or member variable name. NOTE: Ambiguous static import is not allowed. i.e. if you have imported java.lang.System.out and you want to import mypackage.Someclass.out, the compiler will throw an error. Thus you can import only one member out.

serialization in java

What is the purpose of serialization in java?

Serialization is a conversion of an object to a series of byte, so that the object can be easily saved to persistent storage or streamed across a communication link, The byte stream can then be deserialized - converted into a replica of an original object.


Transient : If any variable is defined by using keyword “transient”, then object will not serialize that variable. During deserialization default value of that datatype will be set.
Static : as static variables are class level variables, so it is not serialzed as the object state.

We can do the Serialization process by implementing Serializable interface.

class SerialDemo implements java.io.Serializable

The above step tells the compiler that you are going to implement serialization.
Which basically means that the object is going to be saved or persisted.

use FileOutputStream class and ObjectOutputStream class.

FileOutuptStream Creates an output file stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be write using an ObjectOutputStream.

Save the file using

writeObject(obj);


Program for Serialization


What if you have something top secret, like your password which should not be saved. You mark it as transient!

transient int i;


Create a class Employee to collect information.

package com.javabynataraj.iopack;

class Employee implements java.io.Serializable {
 
 public String name;
 public String address;
 public transient int SSN;
 public int number;

 public void mailCheck() {
    System.out.println("Mailing a check to " + name + " " + address);
  }
}


then create a main class to persist the Employee details in a file.

package com.javabynataraj.iopack;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Serial {
 public static void main(String[] args) {
  Employee e = new Employee();
  e.name = "Muralidhar";
  e.address = "JavabynataraJ,SatyaTechnologies";
  e.SSN = 11111;
  e.number = 101;
  try {
   System.out.println("Before Serialization");
   FileOutputStream fileOut = new FileOutputStream("employee.ser");
   ObjectOutputStream out = new ObjectOutputStream(fileOut);
   out.writeObject(e);
   out.close();
   fileOut.close();
   System.out.println("End of Serialization");
  } catch (IOException i){
   i.printStackTrace();
  }
 }
}

Deserialization is a process of converting the data from files or database converting to Stream of bytes using class Objects.

The Deserialization can be done after serializing the data only.Then we can read the data from the serialized files.

Convert your Serialized file into file form.


File fromFile = new File("Emp.ser");




By using the below two classes we can do the process of deserialization.

#1. FileInputStream
#2. ObjectInputStream

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.


FileInputStream fis = new FileInputStream(fromFile);



An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. This can be Converts the Serialized file into the Object form.


ObjectInputStream ois = new ObjectInputStream(fis);



To get the object of a serialized file we have to typecast into our class Employee to read the values in a file using variable names.


Employee emp = (Employee) ois.readObject();



After that close all the object connections.

You should write the  Employee class already written in Serialization.(check it there)

Program for Deserialization:


package javabynataraj.iopack;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Deserial {
    public static void main(String arg[]) {
        File fromFile = new File("Emp.ser");
        try {
            FileInputStream fis = new FileInputStream(fromFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Employee emp = (Employee) ois.readObject();
            System.out.println("Deserialized data: \n"+ emp.eno + " "+ emp.ename +" "+ emp.esal+" "+emp.eaddr+ "  from Emp.ser");
            ois.close();
        } catch(IOException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        } catch(ClassNotFoundException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        }
    }
}

Referance: shivasoft.in and  javabynataraj.blogspot.in

Ajax call with Strut2

Ajax Call with Strut2
//----- Write in JavaScript---------------------
function findAppointment(strValue) {

 if (typeof XMLHttpRequest != "undefined") {
  xmlHttp = new XMLHttpRequest();
 } else if (window.ActiveXObject) {
  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 if (xmlHttp == null) {
  alert("Browser is campatible ...tht must IE");
 }

 var id = strValue.value;
 var url = "getDetailsAjax"; // URL
 url += "?id=" + id;  // Parameters

 xmlHttp.onreadystatechange = getDts; // get response method
 xmlHttp.open("POST", url, true);
 xmlHttp.send(null);
}

// here you will get the response of your ajax call 
function getDts () {
 if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
  var data = xmlHttp.responseText;
  alert(data);
 }
}


<!—Ajax Struts Configuration Call  -->      
<action name="*Ajax" class="com.ajax.DetailsAction" method="{1}">
 <result type="stream">    
  <param name="inputName">inputeStream</param>
 </result>
</action>

// Action method of DetailsAction
public String getDetailsAjax () throws Exception{
 String ajaxString = new String()
 try {  
  ajaxString += “sandeep”;
  inputeStream = new StringBufferInputStream(ajaxString);
  inputeStream.reset();
 } catch (Exception e) {
  e.printStackTrace();   
 }
 return SUCCESS;
}


Some Nice Oracle Queries

 
To fetch Duplicate Rows

 Select * from emp 
   where rowid notin (select max(rowid) from emp group by empno);
 
Delete nth Row

delete from emp 
  where empno = (select empno from 
    (select empno,rownum from emp group by empno,rownum 
       having rownum = &n));

Select alternate rows

  select * from emp where rowid in 
    (select decode(mod(rownum,2),0,rowid) from emp);

To find last 3 rows

  select * from emp e1 where 3 > 
   (select count(rowid) from emp e
    where e.rowid < e1.rowid);

To find first 3 rows 

 select * from emp where rownum <=3 
 
Select nth row

 select * from emp where rowid in 
       (select decode(rownum,&n,rowid) from emp);
or
     select * from emp where (rowid,&n) in 
       (select rowid,rownum from emp);

Select nth and mth row

   select * from emp where rowid in
   (select decode(rownum,&m,rowid,&n,rowid) from emp);

Find out last n rows in table

  select * from emp where rowid not in
   (select rowid from emp group by rownum,rowid 
     having rownum <= (select count(*) - &n from emp);

Find row between m & n including m & n

  select * from emp where rowid in 
   (select rowid from emp group by rownum having rownum > &n 
    and rownum < &m);

Find last row of table

  select * from emp where rowid in
   (select max(rowid) from emp);

Rename column

 alter table emp rename column empno to eno;

Rename table 

 rename emp to employee;

Employee name starting with s,p,a

  select * from emp where substr(empname,1,1) in ('s','p','a');

Display 2nd highest sal department wise

 select * from emp a where 1 = 
  (select count(distinct sal) from emp b where a.sal < b.sal and a.dept=b.dept);

To create table from existing table without data

 create table emp1 as (select * from emp where 1=2);

Display max sal along with all details

  select * from emp where sal in (select max(sal) from emp);

Last n row

  select * from emp minus select * from emp 
   where rownum <= (select max(rownum)-&n from emp);
 or
  select * from emp e1 where &n > (select count(rowid) from emp e2
   where e1.rowid < e2.rowid );

Delete n row

 Delete form emp where empno = (select empno from (select empno,rownum from emp 
   group by empno,rownum having rownum = &n));

Convert sal into string
 
 select tochar(to_date(sal,'J'),'JSP') salinWord from emp;

Find out null & total nul column

  Note: comm and mgr are the column of table emp

  select sum(decode(comm,null,1,0)) comm_null, sum(decode(mgr,null,1,0)) mgr_null
   sum(comm_null + mgr_null) Total_null from emp;

Find no. of employee working in each dept. & total no. of employee

  select sum(decode(deptno,10,1,1) dept_10, sum(decode(deptno,20,1,1) dept_20,
   sum(decode(deptno,30,1,1) dept_30, sum(decode(deptno,40,1,1) dept_40,
   count(*) total from emp;
 or
  select deptno,count(empno) from emp group by deptno;

No. of employee hired in one month

 select to_char(hiredate,'Mon'),count(hiredate) from emp 
  group by to_char(hiredate,'Mon');

Total no. of column in the table

  select count(*) from col where tname = &tablename; 

To find employee joined on same date

  select * from emp e1 where 2 <= (select count(*) from emp e2 
    where e1.hiredate = e2.hiredate);

To find the no. of employee working under each manager or employee

  select mgr,count(empno) from emp where mgr is not null group by mgr;

Maximun no. of employee working under which employee/manager

  select * from (select mgr,count(empno) No from emp where mgr is not null
   group by mgr) where No = (select max(No) from (select mgr,count(empno) from emp
   where mgr is not null group by mgr));

No. of employee hired on same date

  select hiredate,No from (select hiredate,count(empno) No from emp group by hiredate);

Nth Highest Salary 

  Generic
  SELECT name, salary FROM employee e1 WHERE N-1 = (SELECT COUNT(DISTINCT salary) 
  FROM employee e2 WHERE e2.salary > e1.salary)
  Sql Server 
  SELECT TOP 1 salary FROM 
  ( SELECT DISTINCT TOP N salary FROM employee ORDER BY salary DESC ) AS temp 
  ORDER BY salary
  My Sql
  SELECT salary FROM employee ORDER BY salary DESC LIMIT N-1, 1

  postgres - need to set limit and offset properly
  SELECT salary FROM employee ORDER BY salary DESC LIMIT N-1 OFFSET 1

please try at your end....

Tuesday, September 25, 2012

Lazy/Eager Loading Using Hibernate

Lazy/Eager Loading Using Hibernate
Today's post will focus on why and how we use the concepts known 
as LAZY and EAGER loading in an application and how to use 
Spring's hibernate template to load our LAZY entities in an EAGER 
fashion.

And of course as the title itself suggests, we will show this by 
an example. The scenario is as such;

You are a parent who has a kid with a lot of toys. But the current 
issue is whenever you call him (we assume you have a boy), he comes 
to you with all his toys as well. Now this is an issue since you do 
not want him carrying around his toys all the time.

So being the rationale parent, you go right ahead and define the toys 
of the child as LAZY. Now whenever you call him, he just comes to you 
without his toys.

But you are faced with another issue. When the time comes for a family
trip, you want him to bring along his toys because the kid will be 
bored with the trip otherwise. But since you strictly enforced LAZY 
on the child's toy, you are unable to ask him to bring along the toys. 
This is where EAGER fetching comes into play. Let us first see our 
domain classes.

 
package com.fetchsample.example.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Holds information about the child
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Entity
@Table(name = "CHILD")
@NamedQuery(name = "findChildByName", 
query = "select DISTINCT(chd) from Child chd left join fetch chd.toyList 
where chd.childName=:chdName")
public class Child {

 public static interface Constants {
  public static final String FIND_CHILD_BY_NAME_QUERY = "findChildByName";

  public static final String CHILD_NAME_PARAM = "chdName";
 }

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 /**
  * The primary key of the CHILD table
  */
 private Long childId;

 @Column(name = "CHILD_NAME")
 /**
  * The name of the child
  */
 private String childName;

 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
 /**
  * The toys the child has. We do not want the child to have the 
  * same toy more than once, so we have used a set here.
  */
 private Set toyList = new HashSet();

 public Long getChildId() {
  return childId;
 }

 public void setChildId(Long childId) {
  this.childId = childId;
 }

 public String getChildName() {
  return childName;
 }

 public void setChildName(String childName) {
  this.childName = childName;
 }

 public Set getToyList() {
  return toyList;
 }

 public void addToy(Toy toy) {
  toyList.add(toy);
 }

}

------------------------------------------------

 
package com.fetchsample.example.domain;

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

/**
 * Hols data related to the toys a child possess
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Entity
@Table(name = "TOYS")
public class Toy {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "TOY_ID")
 /**
  * The primary key of the TOYS table
  */
 private Long toyId;

 @Column(name = "TOY_NAME")
 /**
  * The name of the toy
  */
 private String toyName;

 public Long getToyId() {
  return toyId;
 }

 public void setToyId(Long toyId) {
  this.toyId = toyId;
 }

 public String getToyName() {
  return toyName;
 }

 public void setToyName(String toyName) {
  this.toyName = toyName;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((toyName == null) ? 0 : toyName.hashCode());
  return result;
 }

 @Override
 /**
  * Overriden because within the child class we use a Set to
  * hold all unique toys
  */
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Toy other = (Toy) obj;
  if (toyName == null) {
   if (other.toyName != null)
    return false;
  } else if (!toyName.equals(other.toyName))
   return false;
  return true;
 }

 @Override
 public String toString() {
  return "Toy [toyId=" + toyId + ", toyName=" + toyName + "]";
 }

}

So as you can see, we have two simple entities representing the child 
and toy. The child has a one-to-many relationship with the toys which 
means one child can have many toys (oh how i miss my childhood days). 
Afterwards we need to interact with the data, so let us go ahead and 
define out DAO(Data access object) interface and implementation.  

 
package com.fetchsample.example.dao;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fetchsample.example.domain.Child;

/**
 * The basic contract for dealing with the {@link Child} entity
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public interface ChildDAO {

 /**
  * This method will create a new instance of a child in the child table
  * 
  * @param child
  *            the entity to be persisted
  */
 public void persistChild(Child child);

 /**
  * Retrieves a child without his/her toys
  * 
  * @param childId
  *            the primary key of the child table
  * @return the child with the ID passed in if found
  */
 public Child getChildByIdWithoutToys(Long childId);

 /**
  * Retrieves the child with his/her toys
  * 
  * @param childId
  *            the primary key of the child table
  * @return the child with the ID passed in if found
  */
 public Child getChildByIdWithToys(Long childId);

 /**
  * Retrieves the child by the name and with his/her toys
  * 
  * @param childName
  *            the name of the child
  * @return the child entity that matches the name passed in
  */
 public Child getChildByNameWithToys(String childName);

}

--------------------------------------------
 
package com.fetchsample.example.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;

/**
 * The hibernate implementation of our {@link ChildDAO} interface
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildDAOHibernateImpl extends HibernateDaoSupport implements
  ChildDAO {

 /**
  * {@inheritDoc}
  */
 public void persistChild(Child child) {
  getHibernateTemplate().persist(child);
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByIdWithoutToys(Long childId) {
  return getHibernateTemplate().get(Child.class, childId);
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByIdWithToys(Long childId) {
  Child child = getChildByIdWithoutToys(childId);
  /**
   * Since by default the toys are not loaded, we call the hibernate
   * template's initialize method to populate the toys list of that
   * respective child.
   */
  getHibernateTemplate().initialize(child.getToyList());
  return child;
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByNameWithToys(String childName) {
  return (Child) getHibernateTemplate().findByNamedQueryAndNamedParam(
    Child.Constants.FIND_CHILD_BY_NAME_QUERY,
    Child.Constants.CHILD_NAME_PARAM, childName).get(0);

 }

}

A simple contract. I have four main methods. The first one of course 
just persists a child entity to the database.

The second method retrieves the Child by the primary key passed in, 
but does not fetch the toys.

The third method first fetches the Child and then retrieves the 
Child's toys using the Hibernate template's initialize() method. 
Note that when you call the initialize() method, hibernate will 
fetch you LAZY defined collection to the Child proxy you retrieved.

The final method also retrieves the Child's toys, but this time using 
a named query. If we go back to the Child entity's Named query, you 
can see that we have used "left join fetch". It is the keyword fetch 
that actually will initialize the toys collection as well when 
returning the Child entity that qualifies. Finally i have my main 
class to test our functionality;

 
package com.fetchsample.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
import com.fetchsample.example.domain.Toy;

/**
 * A test class
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildTest {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "com/fetchsample/example/spring-context.xml");

  /**
   * First we initialize a child
   */
  Child child = new Child();

  /**
   * A cool ben 10 action figure
   */
  Toy ben10 = new Toy();
  ben10.setToyName("Ben 10 figure");

  /**
   * A even more cooler spider man action figure
   */
  Toy spiderMan = new Toy();
  spiderMan.setToyName("Spider man figure");

  child.setChildName("John");
  /**
   * Add the toys to the collection
   */
  child.addToy(ben10);
  child.addToy(spiderMan);

  ChildDAO childDAO = (ChildDAO) context.getBean("childDAO");

  childDAO.persistChild(child);

  Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L);
  // The following line will throw a lazy initialization error since we have
  // defined fetch type as LAZY in the Child domain class.
  // System.out.println(childWithToys.getToyList().size());

  Child childWithToys = childDAO.getChildByIdWithToys(1L);
  System.out.println(childWithToys.getToyList().size());

  Child childByNameWithToys = childDAO.getChildByNameWithToys("John");

  System.out.println(childByNameWithToys.getToyList().size());

 }
}

--------------------------------------------
 
package com.fetchsample.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
import com.fetchsample.example.domain.Toy;

/**
 * A test class
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildTest {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "com/fetchsample/example/spring-context.xml");

  /**
   * First we initialize a child
   */
  Child child = new Child();

  /**
   * A cool ben 10 action figure
   */
  Toy ben10 = new Toy();
  ben10.setToyName("Ben 10 figure");

  /**
   * A even more cooler spider man action figure
   */
  Toy spiderMan = new Toy();
  spiderMan.setToyName("Spider man figure");

  child.setChildName("John");
  /**
   * Add the toys to the collection
   */
  child.addToy(ben10);
  child.addToy(spiderMan);

  ChildDAO childDAO = (ChildDAO) context.getBean("childDAO");

  childDAO.persistChild(child);

  Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L);
  // The following line will throw a lazy initialization error since we have
  // defined fetch type as LAZY in the Child domain class.
  // System.out.println(childWithToys.getToyList().size());

  Child childWithToys = childDAO.getChildByIdWithToys(1L);
  System.out.println(childWithToys.getToyList().size());

  Child childByNameWithToys = childDAO.getChildByNameWithToys("John");

  System.out.println(childByNameWithToys.getToyList().size());

 }
}

Defining your base Entity as LAZY is a good practice since
in many occasions, you might not want the collections within 
an entity, but just want to interact with the data in your base 
entity. But in the event of you needing the data of your collections,
then you can use either of the methods mentioned before.

Referance: Dinuka Arseculeratne (Dzone)