What is Spring Framework , why we need Spring framework - Simple overview



Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, reusable code.
Spring framework is an open source Java platform and it was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.
Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

Benefits of Using Spring Framework:

Following is the list of few of the great benefits of using Spring Framework:
  • Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is that you do not need an EJB container product such as an application server but you have the option of using only a robust servlet container such as Tomcat or some commercial product.
  • Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you have to worry only about ones you need and ignore the rest.
  • Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.
  • Testing an application written with Spring is simple because environment-dependent code is moved into this framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for injecting test data.
  • Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
  • Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.
  • Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources.
  • Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Blogger Tricks

Hibernate Sessions


A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of the following three states at a given point in time:
  • transient: A new instance of a a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate.
  • persistent: You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.
  • detached: Once we close the Hibernate Session, the persistent instance will become a detached instance.
A Session instance is serializable if its persistent classes are serializable. A typical transaction should use the following idiom:
Session session = factory.openSession();
Transaction tx = null;
try {
   tx = session.beginTransaction();
   // do some work
   ...
   tx.commit();
}
catch (Exception e) {
   if (tx!=null) tx.rollback();
   e.printStackTrace(); 
}finally {
   session.close();
}
If the Session throws an exception, the transaction must be rolled back and the session must be discarded.

Session Interface Methods:

There are number of methods provided by the Session interface but I'm going to list down few important methods only, which we will use in this tutorial. You can check Hibernate documentation for a complete list of methods associated with Session and SessionFactory.
S.N.Session Methods and Description
1Transaction beginTransaction() 
Begin a unit of work and return the associated Transaction object.
2void cancelQuery() 
Cancel the execution of the current query.
3void clear() 
Completely clear the session.
4Connection close() 
End the session by releasing the JDBC connection and cleaning up.
5Criteria createCriteria(Class persistentClass) 
Create a new Criteria instance, for the given entity class, or a superclass of an entity class.
6Criteria createCriteria(String entityName) 
Create a new Criteria instance, for the given entity name.
7Serializable getIdentifier(Object object) 
Return the identifier value of the given entity as associated with this session.
8Query createFilter(Object collection, String queryString) 
Create a new instance of Query for the given collection and filter string.
9Query createQuery(String queryString) 
Create a new instance of Query for the given HQL query string.
10SQLQuery createSQLQuery(String queryString) 
Create a new instance of SQLQuery for the given SQL query string.
11void delete(Object object) 
Remove a persistent instance from the datastore.
12void delete(String entityName, Object object) 
Remove a persistent instance from the datastore.
13Session get(String entityName, Serializable id) 
Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.
14SessionFactory getSessionFactory() 
Get the session factory which created this session.
15void refresh(Object object) 
Re-read the state of the given instance from the underlying database.
16Transaction getTransaction() 
Get the Transaction instance associated with this session.
17boolean isConnected() 
Check if the session is currently connected.
18boolean isDirty() 
Does this session contain any changes which must be synchronized with the database?
19boolean isOpen() 
Check if the session is still open.
20Serializable save(Object object) 
Persist the given transient instance, first assigning a generated identifier.
21void saveOrUpdate(Object object) 
Either save(Object) or update(Object) the given instance.
22void update(Object object) 
Update the persistent instance with the identifier of the given detached instance.
23void update(String entityName, Object object) 
Update the persistent instance with the identifier of the given detached instance.

Hibernate Configuration

Hibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml.
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required. This file is kept in the root directory of your application's classpath.

Hibernate Properties:

Following is the list of important properties you would require to configure for a databases in a standalone situation:
S.N.Properties and Description
1hibernate.dialect 
This property makes Hibernate generate the appropriate SQL for the chosen database.
2hibernate.connection.driver_class 
The JDBC driver class.
3hibernate.connection.url 
The JDBC URL to the database instance.
4hibernate.connection.username 
The database username.
5hibernate.connection.password 
The database password.
6hibernate.connection.pool_size 
Limits the number of connections waiting in the Hibernate database connection pool.
7hibernate.connection.autocommit 
Allows autocommit mode to be used for the JDBC connection.
If you are using a database along with an application server and JNDI then you would have to configure the following properties:
S.N.Properties and Description
1hibernate.connection.datasource 
The JNDI name defined in the application server context you are using for the application.
2hibernate.jndi.class 
The InitialContext class for JNDI.
3hibernate.jndi.<JNDIpropertyname> 
Passes any JNDI property you like to the JNDI InitialContext.
4hibernate.jndi.url 
Provides the URL for JNDI.
5hibernate.connection.username 
The database username.
6hibernate.connection.password 
The database password.

Hibernate with MySQL Database:

MySQL is one of the most popular open-source database systems available today. Let us createhibernate.cfg.xml configuration file and place it in the root of your application's classpath. You would have to make sure that you have testdb database available in your MySQL database and you have a user test available to access the database.
The XML configuration file must conform to the Hibernate 3 Configuration DTD, which is available from http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <property name="hibernate.dialect">
      org.hibernate.dialect.MySQLDialect
   </property>
   <property name="hibernate.connection.driver_class">
      com.mysql.jdbc.Driver
   </property>

   <!-- Assume test is the database name -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/test
   </property>
   <property name="hibernate.connection.username">
      root
   </property>
   <property name="hibernate.connection.password">
      root123
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>
The above configuration file includes <mapping> tags which are related to hibernate-mapping file and we will see in next chapter what exactly is a hibernate mapping file and how and why do we use it. Following is the list of various important databases dialect property type:
DatabaseDialect Property
DB2org.hibernate.dialect.DB2Dialect
HSQLDBorg.hibernate.dialect.HSQLDialect
HypersonicSQLorg.hibernate.dialect.HSQLDialect
Informixorg.hibernate.dialect.InformixDialect
Ingresorg.hibernate.dialect.IngresDialect
Interbaseorg.hibernate.dialect.InterbaseDialect
Microsoft SQL Server 2000org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008org.hibernate.dialect.SQLServer2008Dialect
MySQLorg.hibernate.dialect.MySQLDialect
Oracle (any version)org.hibernate.dialect.OracleDialect
Oracle 11gorg.hibernate.dialect.Oracle10gDialect
Oracle 10gorg.hibernate.dialect.Oracle10gDialect
Oracle 9iorg.hibernate.dialect.Oracle9iDialect
PostgreSQLorg.hibernate.dialect.PostgreSQLDialect
Progressorg.hibernate.dialect.ProgressDialect
SAP DBorg.hibernate.dialect.SAPDBDialect
Sybaseorg.hibernate.dialect.SybaseDialect
Sybase Anywhereorg.hibernate.dialect.SybaseAnywhereDialect

Hibernate Environment Setup

This chapter will explain how to install Hibernate and other associated packages to prepare a develop environment for the Hibernate applications. We will work with MySQL database to experiment with Hibernate examples, so make sure you already have setup for MySQL database. For a more detail on MySQL you can check our MySQL Tutorial.

Downloading Hibernate:

It is assumed that you already have latest version of Java is installed on your machine. Following are the simple steps to download and install Hibernate on your machine.
  • Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.
  • Download the latest version of Hibernate from http://www.hibernate.org/downloads.
  • At the time of writing this tutorial I downloaded hibernate-distribution-3.6.4.Final and when you unzip the downloaded file it will give you directory structure as follows.
Hibernate Directories

Installing Hibernate:

Once you downloaded and unzipped the latest version of the Hibernate Installation file, you need to perform following two simple steps. Make sure you are setting your CLASSPATH variable properly otherwise you will face problem while compiling your application.
  • Now copy all the library files from /lib into your CLASSPATH, and change your classpath variable to include all the JARs:
  • Finally copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of the installation and is the primary JAR that Hibernate needs to do its work.

Hibernate Prerequisites:

Following is the list of the packages/libraries required by Hibernate and you should install them before starting with Hibernate. To install these packages you would have to copy library files from /lib into your CLASSPATH, and change your CLASSPATH variable accordingly.
S.N.Packages/Libraries
1dom4j - XML parsing www.dom4j.org/
2Xalan - XSLT Processor http://xml.apache.org/xalan-j/
3Xerces - The Xerces Java Parser http://xml.apache.org/xerces-j/
4cglib - Appropriate changes to Java classes at runtime http://cglib.sourceforge.net/
5log4j - Logging Faremwork http://logging.apache.org/log4j
6Commons - Logging, Email etc. http://jakarta.apache.org/commons
7SLF4J - Logging Facade for Java http://www.slf4j.org

Hibernate Architecture

The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.
Following is a very high level view of the Hibernate Application Architecture.

Following is a detailed view of the Hibernate Application Architecture with few important core classes.

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
Following section gives brief description of each of the class objects involved in Hibernate Application Architecture.

Configuration Object:

The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components:
  • Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
  • Class Mapping Setup
    This component creates the connection between the Java classes and database tables..

SessionFactory Object:

Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.

Session Object:

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

Transaction Object:

A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

Query Object:

Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Criteria Object:

Criteria object are used to create and execute object oriented criteria queries to retrieve objects.