Hibernate Notes


  • The Hibernate project has the structure as shown in the figure as above.
  • We need one hibernate.cfg.xml file for hibernate configuration which handles connection pulling and other stuff like driver name, username of the database, password of the database, and the following properties..


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"

  <property name="hibernate.connection.driver_class">

  <property name="hibernate.connection.url">

  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password"></property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="">update</property>
  <!-- Mapping files -->
  <mapping resource="contact.hbm.xml"/>

  • Here the Hibernate tutorial is the database supposed to be created at local host.
  • The dialect property says that we are suing the MySQL database.
  • The show sql property lets us see the comments at the console which ultimately increases readability.
  • Every Class file having the attributes have a classname.hbm.xml file which is the conf file for mapping between POJO and the database. For example we have "contact.hbm.xml" file for contact class.
  • Hibernate accesses all the data through POJO objects and then interacts with the database. For interacting with the database it uses the HQL(Hibernate Query Language)
  • Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column.

Code for

  * Java Class to map to the datbase Contact Table
public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

 @return Email
  public String getEmail() {
  return email;

 @return First Name
  public String getFirstName() {
  return firstName;

 @return Last name
  public String getLastName() {
  return lastName;

 @param string Sets the Email
  public void setEmail(String string) {
  email = string;

 @param string Sets the First Name
  public void setFirstName(String string) {
  firstName = string;

 @param string sets the Last Name
  public void setLastName(String string) {
  lastName = string;

 @return ID Returns ID
  public long getId() {
  return id;

 @param l Sets the ID
  public void setId(long l) {
  id = l;

Mapping the Contact class with the Contact Table.

Code for Contact.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

  <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>

  <property name="firstName">
   <column name="FIRSTNAME" />
  <property name="lastName">
  <column name="LASTNAME"/>
  <property name="email">
  <column name="EMAIL"/>




Then we need to create a hibernatetutorial database using MySQL running at localhost.

For updating or inserting the data in the database we first need to create the session of hibernate. For that we need to use hibernate session factory which returns the session for hibernate.

The hibernate-session is the main runtime interface between java and Hibernate.

The most important method for this is;.

The code for

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


 * Hibernate example to inset data into Contact table
public class FirstExample {
  public static void main(String[] args) {
  Session session = null;

  // This step will read hibernate.cfg.xml 

and prepare hibernate for use
  SessionFactory sessionFactory = new 

 session =sessionFactory.openSession();
  //Create new instance of Contact and set 

values in it by reading them from form object
 System.out.println("Inserting Record");
  Contact contact = new Contact();
  }catch(Exception e){
  // Actual contact insertion will happen at this step


Dependency Injection (DI)

The first reference to what would eventually become Dependency Injection appeared in 1994 in a paper by Robert C. Martin called "The Dependency Inversion Principle".

In "The Dependency Inversion Principle" (or DIP), the author states the three defining factors of "bad code":

  • It is hard to change because every change affects too many other parts of the system (Rigidity)
  • When you make a change, unexpected parts of the system break (Fragility)
  • It is hard to reuse in another application because it cannot be disentangled from the current application (Immobility)

According to Martin, interdependency causes these coding problems (we'll call them RFI for Rigidity, Fragility, and Immobility). To fix RFI issues in your OO code, DIP has two basic rules:


1. High level modules should not depend upon low level modules, both should depend upon abstractions.

In other words, high level modules – which contain your business logic and all of the important meat of your application – should not depend on lower level components. The reason for this is if these lower level components were to change, the changes might affect the higher level components as well. This is the defining concept behind dependency inversion, that the prevailing wisdom of having higher-level modules dependent on lower-level modules is in fact a bad idea.

2. Abstractions should not depend upon details, details should depend upon abstractions.

This is another way to say that before you begin coding to the abstraction – the interface or abstract class – you should find the common behaviors in the code and work backwards. Your interface abstraction should cater to the intersection between the needs of your business logic and the common behaviors of the lower level modules. You should also leave the details of how these behaviors are implemented to the implementation classes.

Spring Light weighted Framework


  • Loose coupling with dependency injection
  • Declarative programming with AOP
  • Boilerplate reduction with templates
  • Minimally invasive and POJO-oriented

Spring Keywords

  • Spring Web Flow
  • BlazeDS Integration
  • Spring-WS
  • Spring Security
  • Spring-DM
  • DmServer
  • Bundlor
  • TcServer
  • Spring Batch
  • Spring Integration
  • Spring LDAP
  • Spring IDE / STS
  • Spring Rich Client
  • Spring .NET
  • Spring BeanDoc
  • Groovy/Grails

MVC Design Patterns


MVC is an architectural pattern that is used when developing interactive application such as a shopping cart on the Internet.


User interfaces change often, especially on the internet where look-and-feel is a competitive issue. Also, the same information is presented in different ways. The core business logic and data is stable.


Use the concept of dividing the concerns to divide the application into three areas

  • Model :- Encapsulates the core data and the functionality
  • View :- Encapsulates the presentation of the data there can be many views of the common data
  • Controller:- accepts input from the user and makes request from the model for the data to produce a new view

The model represents the structure of the data and the operations that can be performed on that data.

The view represents the data that is in a presentable format.

The controller translates the user action like mouse events, submit, keystrokes, words spoken with user input to call the call the specific operation with the model.

MVC example- Java Pet Store

It demonstrates a real-world approach to application development, where the presentation of data is separated from the process of obtaining data from objects which interact with the enterprise or database tier.

The design can be divided into the following tiers:

  • Client Tier
  • Web tier
  • Enterprise Bean Tier
  • Enterprise Information System Tier


The Client Tire is the only part which is visible to the end user of the application so it handles the view part it is also connected to the other tiers using some well defined interfaces.

The separate Client tier design provides flexibility and extensibility .


Variable arguments

You can use a construct called varargs to pass an arbitrary number of values to a method.

You will most commonly see varargs with the printing methods; for example, this printf method:

public PrintStream printf(String format, Object... args)


allows you to print an arbitrary number of objects. It can be called like this:

System.out.printf("%s: %d, %s%n", name, idnum, address);


or like this

System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, mail);

or with yet a different number of arguments.


Overloading of Methods

  • The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists
  • You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
  • The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.


  • Note: 
    • Overloaded methods should be used sparingly, as they can make code much less readable.


Copying arrays using System class method

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src,

int srcPos,

Object dest,

int destPos,

int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array:


class ArrayCopyDemo {

public static void main(String[] args) {

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',

             'i', 'n', 'a', 't', 'e', 'd' };

char[] copyTo = new char[7];


System.arraycopy(copyFrom, 2, copyTo, 0, 7);

System.out.println(new String(copyTo));



The output from this program is:


Java Variables

Types of Variables

  • Instance Variable: Non-static fields are also known as instance variables because their values are unique to each instance of a class.
  • Class Variables:class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence; regardless of how many times the class has been instantiated.
  • Local Variables: Variables between the opening and closing braces of a method.
  • Parameters: The Arguments of a method or a constructor.

Naming Conventions

  • By convention it should start with the letter.
  • Avoid $ and _ characters in the names.
  • Whitespaces are not allowed.
  • Keyword or any reserved word should not be used.
  • For constants separate the words with the _.

Object initialization

  • As with class initialization, the simplest kind of object initialization is automatic initialization of object fields to default values.
  • Example:

    class ObjectInitializationDemo1


    boolean b;

    byte by;

    char c;

    double d;

    float f;

    int i;

    long l;

    short s;

    String st;

    public static void main (String [] args)


    ObjectInitializationDemo1 oid1 = new ObjectInitializationDemo1 ();

    System.out.println ("oid1.b = " + oid1.b);

    System.out.println (" = " +;

    System.out.println ("oid1.c = " + oid1.c);

    System.out.println ("oid1.d = " + oid1.d);

    System.out.println ("oid1.f = " + oid1.f);

    System.out.println ("oid1.i = " + oid1.i);

    System.out.println ("oid1.l = " + oid1.l);

    System.out.println ("oid1.s = " + oid1.s);

    System.out.println (" = " +;



  • Output

    b = false

    by = 0

    c =  

    d = 0.0

    f = 0.0

    i = 0

    l = 0

    s = 0

    st = null


  • There is no class loading and byte code verifying in between.
  • The same way the explicit assignment is done.
  • The default constructer initializes the contents of the object. For that it uses <init> methodfrom JVM perspective
  • The same way as in class initialization the object initialization also allows us to refer to the previously initialized field.
  • Object Block Initailazation


          System.out.println ("Initializing object " + hashCode ());

          int localVariable = 1;


  • In many situations, you will not use object block initializers because you can use constructors to perform complex initialization tasks. 
  • For situations like:  Anonymous inner classes often require object block initializers to perform complex initialization tasks.

    Anonymous inner classes require object block initializers because anonymous inner classes have no names, constructors take on the names of their classes, and you cannot declare constructors in classes that have no names.

  • In the case of hierarchies the class at the top most level is first initialized.
  • In object field/block initialization , one can access the field of the subclass but at that time the explicit value is not assigned so it will give us default value.


Class initialization

  • Although we tend to think of initialization in terms of assigning values to variables, initialization is so much more. 
  • For example, initialization might involve opening a file and reading its contents into a memory buffer, registering a database driver, preparing a memory buffer to hold an image's contents, acquiring the resources necessary for playing a video, and so on.
  • Java supports initialization via language features collectively known as initializers.
  • Class initialization is different from Object initialization and it happens before Object initialization.


  • Class Initialization
    • A program contains no of classes, before the execution of java program the class loader loads the public class having the PSVM.
    • Then the byte code verifier verifies the class.
    • Then class initializes.
    • The class fields are set to default values.
    • For Example:


      • static boolean b;//flase
      • static byte by;//0
      • static char c;//
      • static double d;//0.0
      • static float f;//0.0
      • static int i;//0
      • static long l;//0
      • static short s;//0
      • static String st;//null


  • We can also explicitly assign values to the class fields.
  • Those values are assigned to the fields just after the class is loaded and before any user defined method including main executes.
  • This initialization is done using <clinit>method of the JVM. It uses machine level instructions to assign those values.
  • Although a subsequently declared class field can refer to a previously declared class field, the reverse is not true: You cannot declare a class field initializer that refers to a class field declared later in source code. In other words, Java does not permit forward references with class field initializers, as the following code fragment demonstrates:
    • static int second = 1 + first;
    • static int first = 3;
  • In the cases when you need to read the contents of the file before the main method executes then we need to use the static block.
    • static
    •    {
    •       System.out.println ("Acquiring filenames");
    •       filenames = new File (".").list ();
    •       System.out.println ("Filenames acquired");
    •    }
  • Class block initializers are useful. For example, Sun's JDBC (Java Database Connectivity) API uses class block initializers to simplify database driver registration. Consider the following code fragment:
    • Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
  • Any variable declared in the block is having the scope only upto that block.
  • JVM allows us to declare any constant field without any explicit initializer, but u have to initialize it before its first use.
    • class ClassInitializationDemo5
    • {
    •    final static double PI;
    •    static
    •    {
    •       PI = 3.14159;
    •       int i;
    •       for (i = 0; i < 5; i++)
    •            System.out.println (i);
    •    }
    •    static int j = i;//this vl cause problem as the I is local to that block
    •    public static void main (String [] args)
    •    {
    •       System.out.println ("PI = " + PI);//this vl show 3.14 as the initialization is done in static block
    •    }
    • }
  • When a class hierarchy is involved, the compiler creates a separate<clinit> method for each class in that hierarchy. At runtime, the JVM loads all hierarchy classes and calls their <clinit> methods in a top-to-bottom order. 

Class Loading while running JVM

  • The Order is
    • Bootstrap classes - Classes that comprise the Java platform, including the classes in rt.jar and several other important jar files.
    • Extension classes - Classes that use the Java Extension mechanism. These are bundled as .jar files located in the extensions directory.
    • User classes - Classes defined by developers and third parties that do not take advantage of the extension mechanism. You identify the location of these classes using the -classpath option on the command line (the preferred method) or by using the CLASSPATH environment variable. 

Wild Cards while specifying the class path

  • A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo, use either foo; foo/* or foo/*;foo. The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo, or vice versa.
  • Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo, not in foo/bar, foo/baz, etc.
  • If u want to load jars files or class file in a specific order that u have to specify the list itself in the class path but not using the wild cards.
  • Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar, b.jar, and c.jar, then the class path foo/* is expanded into foo/a.jar; foo/b.jar; foo/c.jar, and that string would be the value of the system property java.class.path.
  • The CLASSPATH environment variable is not treated any differently from the -class path (or -cp) command-line option. That is, wildcards are honoured in all these cases. However, class path wildcards are not honoured in the Class-Path jar-manifest header.

JDK and JRE File Structure

Assuming the JDK software is installed at c:\jdk1.7.0, here are some of the most important directories:


Root directory of the JDK software installation. Contains copyright, license, and README files. Also contains, the archive of source code for the Java platform.


Executable files for the development tools contained in the Java Development Kit. The PATH environment variable should contain an entry for this directory. For more information on the tools, see the JDK Tools.


Files used by the development tools. These include tools.jar, which contains non-core classes for support of the tools and utilities in the JDK. Also includes dt.jar, the DesignTime archive of BeanInfo files that tell interactive development environments (IDE's) how to display the Java components and how to let the developer customize them for an application.


Root directory of the Java runtime environment used by the JDK development tools. The runtime environment is an implementation of the Java platform. This is the directory represented by the java.home system property.


Executable files and DLLs for tools and libraries used by the Java platform. The executable files are identical to files in /jdk1.7.0/bin. The java launcher tool serves as an application launcher (and replaced the old jretool that shipped with 1.1 versions of the JDK). This directory does not need to be in the PATH environment variable.


Contains the DLL files used by the Java HotSpot™ Client Virtual Machine.


Contains the DLL files used by the Java HotSpot™ Server Virtual Machine.


Code libraries, property settings, and resource files used by the Java runtime environment. For example:


Default installation directory for Extensions to the Java platform.

  • localedata.jar -- locale data for java.text and java.util.


Contains files used for security management. These include the security policy (java.policy) and security properties ( files.


Jar files containing support classes for applets can be placed in the lib/applet/ directory. This reduces startup time for large applets by allowing applet classes to be pre-loaded from the local file system by the applet class loader, providing the same protections as if they had been downloaded over the net.


Contains TrueType font files for use by the platform.

Additional Files and Directories

This section describes additional files and directories.


Archive containing source code for the Java platform.


Contains Java DB.


Examples, with source code, that show you how to program for the Java platform.


Applets that can be used on a web page.


Examples that use Java 2D™ and JFC\Swing functionality.


Examples of using the Java Platform Debugging Architecture. Includes source code for the javadt and jdb utilities.


Contains demos for use with the Java Plug-in product.


C-language header files that support native-code programming using the Java Native Interface and the Java Virtual Machine Debugger Interface.


Basic Tools

These tools are the foundation of the JDK. They are the tools you use to create and build applications.

Tool Name

Brief Description

Links to Reference Pages


Run and debug applets without a web browser.

[Solaris and Linux] [Windows]


Annotation processing tool.
See Annotation Processing Tool for program annotation processing.

[Solaris, Linux, and Windows]


Utility to detect Jar conflicts.

[Solaris and Linux] [Windows]


Create and manage Java Archive (JAR) files.
See Java Archive Files page for the JAR specification.

[Solaris and Linux] [Windows]


The launcher for Java applications. In this release, a single launcher is used both for development and deployment.
The old deployment launcher, jre, is no longer provided.

[Solaris and Linux] [Windows]


The compiler for the Java programming language.

[Solaris and Linux] [Windows]


API documentation generator.
See Javadoc Tool page for doclet and taglet APIs.

[Solaris and Linux] [Windows]


C header and stub generator. Used to write native methods.

[Solaris and Linux] [Windows]


Class file disassembler

[Solaris and Linux] [Windows]


The Java Debugger.
See JPDA for the debugger architecture specifications.

[Solaris and Linux] [Windows]

Security Tools

These security tools help you set security policies on your system and create apps that can work within the scope of security policies set at remote sites.

Tool Name

Brief Description

Links to Reference Pages


Manage keystores and certificates.

[Solaris and Linux] [Windows]


Generate and verify JAR signatures.

[Solaris and Linux] [Windows]


GUI tool for managing policy files.

[Solaris and Linux] [Windows]

These security tools help you obtain, list, and manage Kerberos tickets.

Tool Name

Brief Description

Links to Reference Pages


Tool for obtaining Kerberos v5 tickets. Equivalent functionality is available on the Solaris operating system via the kinit tool. For example, for Solaris 11, see thekinit reference page.



Command-line tool to list entries in credential cache and key tab. Equivalent functionality is available on the Solaris operating system via the klist tool. For example, for Solaris 11, see the klist reference page.



Command-line tool to help the user manage entires in the key table. Equivalent functionality is available on the Solaris operating system via the kadmin tool. For example, for Solaris 11, see the kadmin reference page.


Internationalization Tools

This tool helps to create localizable apps.

Tool Name

Brief Description

Links to Reference Pages


Convert text to Unicode Latin-1.

[Solaris and Linux] [Windows]

Remote Method Invocation (RMI) Tools

These tools help to create apps that interact over the Web or other network.

Tool Name

Brief Description

Links to Reference Pages


Generate stubs and skeletons for remote objects.

[Solaris and Linux] [Windows]


Remote object registry service.

[Solaris and Linux] [Windows]


RMI activation system daemon.

[Solaris and Linux] [Windows]


Return class serialVersionUID.

[Solaris and Linux] [Windows]

Java IDL and RMI-IIOP Tools

These tools are used when creating applications that use OMG-standard IDL and CORBA/IIOP.

Tool Name

Brief Description


Provides access to the naming service.


Generates .java files that map an OMG IDL interface and enable an application written in the Java programming language to use CORBA functionality.


Provides support for clients to transparently locate and invoke persistent objects on servers in the CORBA environment. ORBD is used instead of the Transient Naming Service, tnameserv. ORBD includes both a Transient Naming Service and a Persistent Naming Service. The orbd tool incorporates the functionality of a Server Manager, an Interoperable Naming Service, and a Bootstrap Name Server. When used in conjunction with the servertool, the Server Manager locates, registers, and activates a server when a client wants to access the server.


Provides ease-of-use interface for the application programmers to register, unregister, startup, and shutdown a server.

Java Deployment Tools

Utilities for use in conjunction with deployment of java applications and applets on the web.

Tool Name

Brief Description


Transforms a JAR file into a compressed pack200 file using the Java gzip compressor. The compressed packed files are highly compressed JARs, which can be directly deployed, saving bandwidth and reducing download time.


Transforms a packed file produced by pack200 into a JAR file.

Java Web Start Tools

Utilities for use in conjunction with Java Web Start.

Tool Name

Brief Description


Command line tool for launching Java Web Start and setting various options.
See Java Web Start Guide for more information.

Java Troublshooting, Profiling, Monitoring and Management Tools

Tool Name

Brief Description


A JMX-compliant graphical tool for monitoring a Java virtual machine. It can monitor both local and remote JVMs. It can also monitor and manage an application.
See Monitoring and Management for the Java Platform for more information.

Java Web Services Tools

Tool Name

Brief Description


Schema generator for Java Architecture for XML Binding.


Tool to generate JAX-WS portable artifacts.


Tool to generate JAX-WS portable artifacts.


Binding compiler for Java Ardchitecture for XML Binding.

Monitoring Tools

You can use the following tools to monitor JVM performance statistics. The tools described in this section are unsupported and experimental, and should be used with that in mind. They may not be available in future JDK versions.

These tools are supported on all platforms except Windows 98 and Windows ME.

Tool Name

Brief Description


Experimental: JVM Process Status Tool - Lists instrumented HotSpot Java virtual machines on a target system.


Experimental: JVM Statistics Monitoring Tool - Attaches to an instrumented HotSpot Java virtual machine and collects and logs performance statistics as specified by the command line options.


Experimental: JVM jstat Daemon - Launches an RMI server application that monitors for the creation and termination of instrumented HotSpot Java virtual machines and provides a interface to allow remote monitoring tools to attach to Java virtual machines running on the local system.

Troubleshooting Tools

The following tools can be used for specific troubleshooting tasks. The tools described in this section are unsupported and experimental in nature and should be used with that in mind. They may not be available in future JDK versions.

Some of these tools are not currently available on Windows platforms.

Tool Name

Brief Description


Experimental - Configuration Info for Java - Prints configuration information for a given process or core file or a remote debug server.


Experimental - Heap Dump Browser - Starts a web server on a heap dump file (eg, produced by jmap -dump), allowing the heap to be browsed.


Experimental - Memory Map for Java - Prints shared object memory maps or heap memory details of a given process or core file or a remote debug server.


Experimental - Serviceability Agent Debug Daemon for Java - Attaches to a process or core file and acts as a debug server.


Experimental - Stack Trace for Java - Prints a stack trace of threads for a given process or core file or remote debug server.

Refer to the Java™ SE Troubleshooting web site for descriptions of tools, options, and other information to use in analyzing problems. The documents at this site contain suggestions about what to try before submitting a bug report and what data to collect for a report.

Scripting Tools

The following tool can be used to run scripts that interact with the Java platfrom. This tool is unsupported and experimental in nature and should be used with that in mind. It might not be available in future JDK versions.

Tool Name

Brief Description


Experimental - Script shell for Java - Runs a script.