Saturday, January 22, 2011

An Introduction to Hibernate and Spring: Part 2

Object relational mapping
As the previous discussion shows, we are looking for a solution that enables applications to work with the object representation of the data in database tables, rather than dealing directly with that data. This approach isolates the business logic from any relational issues that might arise in the persistence layer. The strategy to carry out this isolation is generally called object/relational mapping (O/R Mapping, or simply ORM).
A broad range of ORM solutions have been developed. At the basic level, each ORM framework maps entity objects to JDBC statement parameters when the objects are persisted, and maps the JDBC query results back to the object representation when they are retrieved. Developers typically implement this framework approach when they use pure JDBC. Furthermore, ORM frameworks often provide more sophisticated object mappings, such as the mapping of inheritance hierarchy and object association, lazy loading, and caching of the persistent objects. Caching enables ORM frameworks to hold repeatedly fetched data in memory, instead of being fetched from the database in the next requests, causing deficiencies and delayed responses, the objects are returned to the application from memory. Lazy loading, another great feature of ORM frameworks, allows an object to be loaded without initializing its associated objects until these objects are accessed.
ORM frameworks usually use mapping definitions, such as metadata, XML files, or Java annotations, to determine how each class and its persistent fields should be mapped onto database tables and columns. These frameworks are usually configured declaratively, which allows the production of more flexible code.
Many ORM solutions provide an object query language, which allows querying the persistent objects in an object-oriented form, rather than working directly with tables and columns through SQL. This behavior allows the application to be more isolated from the database properties.

Hibernate as an O/R Mapping solution

For a long time, Hibernate has been the most popular persistence framework in the Java community. Hibernate aims to overcome the already mentioned impedance mismatch between object-oriented applications and relational databases.
With Hibernate, we can treat the database as an object-oriented store, thereby eliminating mapping of the object-oriented and relational environments. Hibernate is a mediator that connects the object-oriented environment to the relational environment. It provides persistence services for an application by performing all of the required operations in the communication between the object-oriented and relational environments. Storing, updating, removing, and loading can be done regardless of the objects persistent form. In addition, Hibernate increases the application's effectiveness and performance, makes the code less verbose, and allows the code to be more focused on business rules than persistence logic. The following screenshot depicts Hibernates role in persistence:
Spring Persistence with Hibernate
Hibernate fully supports object orientation, meaning all aspects of objects, such as association and inheritance, are properly persisted. Hibernate can also persist object navigation, that is, how an object is navigable through its associated objects. It caches data that is fetched repeatedly and provides lazy loading, which notably enhances database performance. As you will see, Hibernate provides caches in two levels: first-level built-in, and second-level pluggable cache strategies. Th e first-level cache is a required property for any ORM to preserve object consistency. It guaranties that the application always works with consistent objects. This is originated from the fact that many threads in the application use the ORM to persist the objects which might potentially be associated to the same table rows in the database. The following screenshot depicts the role of a cache when using Hibernate:
Spring Persistence with Hibernate
Hibernate provides its own query language, which is Hibernate Query Language (HQL). At runtime, HQL expressions are transformed to their corresponding SQL statements, based on the database used. Because databases may use different versions of SQL and may expose different features, Hibernate presents a new concept, called an SQL dialect, t o distinguish how databases differ. Furthermore, Hibernate allows SQL expressions to be used either declaratively or programmatically, which is useful in specific situations when Hibernate does not satisfy application persistence requirements.
Hibernate keeps track of object changes through snapshot comparisons to prevent unnecessary updating.

Other O/R Mapping solutions

Although Hibernate is the most popular persistence framework, many other frameworks do exist. Some of these are explained as follows:
  • Enterprise JavaBeans (EJB): It is a standard J2EE (J ava 2 Enterprise Edition) technology that defines a different type of persistence by presenting entity beans. Mostly, for declarative middleware services that are provided by the application server, such as transactions, EJB may be preferred for architecture. However, due to its complexity, nontransparent persistence, and need for a container (all of which make it difficult to implement, test, and maintain), EJB is less often used than other persistence frameworks.
  • iBatis SQL Map: It is a result set–mapping framework which works at the SQL level, allowing SQL string definitions with parameter placeholders in XML files. At runtime, the placeholders are filled with runtime values, either from simple parameter objects, JavaBeans properties, or a parameter map. To their advantage, SQL maps allow SQL to be fully customized for a specific database. To their disadvantage, however, these maps do not provide an abstraction from the specific features of the target database.
  • Java Data Objects (JDO): It is a specification for general object persistence in any kind of data store, including relational databases and object-oriented databases. Most JDO implementations support using metadata mapping definitions. JDO provides its own query language, JDOQL, and its own strategy for change detection.
  • TopLink: It provides a visual mapping editor (Mapping Workbench) and offers a particularly wide range of object, relational mappings, including a complete set of direct and relational mappings, object-to-XML mappings, and JAXB (Java API for XML Binding) support. TopLink provides a rich query framework that supports an object-oriented expression framework, EJB QL, SQL, and stored procedures. It can be used in either a JSE or a JEE environment.
Hibernate designers has borrowed many Hibernate concepts and useful features from its ancestors

Hibernate versus other frameworks

Unlike the frameworks just mentioned, Hibernate is easy to learn, simple to use, comprehensive, and (unlike EJB) does not need an application server. Hibernate is well documented, and many resources are available for it. Downloaded more than three million times, Hibernate is used in many applications around the world. To use Hibernate, you need only J2SE 1.2 or later, and it can be used in stand-alone or distributed applications.
The current version of Hibernate is 3, but the usage and configuration of this version are very similar to version 2. Most of the changes in Hibernate 3 are compatible with Hibernate 2.
Hibernate solves many of the problems of mapping objects to a relational environment, isolating the application from getting involved in many persistence issues. Keep in mind that Hibernate is not a replacement for JDBC. Rather, it can be thought of as a tool that connects to the database through JDBC and presents an object-oriented, application-level view of the database.


Hibernate architecture

The following screenshot depicts the main participants in the Hibernate architecture:
Spring Persistence with Hibernate
As the screenshot shows, the main players are Hibernate configuration file(s), mapping definitions, and persistent objects. At the heart of Hibernate is its configuration. This configuration is always presented by an XML, or a properties file and includes the relevant database information, such as database username, password, URL, driver class, and SQL dialect that Hibernate needs for connecting to the database, communicating with it, and performing persistence operations.
Persistent objects form another part of the Hibernate architecture. These objects are what we will persist in the database. These entity objects and their classes, do not need to exhibit any special behavior, except that they must follow some POJO rules.
In addition to the Hibernate configuration file and the persistent objects, Hibernate's architecture uses other XML documents, which define how application objects should be mapped to database tables. These documents specify the respective table of each entity class, the mapping of each class's field to its respective table column, and sometimes other mapping information, such as object associations and inheritance. These files have a simple syntax, making them easy to develop and maintain. However, some utility tools that ship with Hibernate let you automatically generate the mapping files, based on the application classes or database schema, and also allow you to modify them in a graphic tool.
Although these objects are the main players in the Hibernate architecture, a Hibernate application's runtime architecture is not limited to them. The most significant runtime objects are Configuration, SessionFactory, Session, and Transaction.
Hibernate can be used as simply as follows to store or retrieve a Student object:
Configuraion cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Student student = ...//a new instantiated student object
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(student);
tx.commit();
session.close();
Here, we have just configured Hibernate, started a transaction, stored the student object, committed the transaction, and finally disconnected from Hibernate. These are actually the required operations to interact with Hibernate. The configuration includes setting up Hibernate to work with a particular database with special behavior. Every Hibernate interaction should be done inside a transaction, which justifies the next step.

What is Spring

Now that you've read a bit about Hibernate's background, it is time to look at Spring and what it has to offer.
Spring is an ambitious framework that aims to be a complete solution for entire JEE applications. Unlike Hibernate, which works merely on the persistence tier, Spring is a multitier framework which offers a wide range of services. It makes JEE development easier, by providing a clean separation of concerns, decoupling an application's components, and minimizing complexities typically encountered in sophisticated JEE environments.
Choosing an appropriate solution for a Java application, particularly when it is built with open-source tools, is a common challenge in application design. This is another challenge that Spring aims to address. The challenge starts when you encounter a large number of open-source technologies that may be used for the same purpose, such as Struts, WebWork, JSF, or Tapestry for web, and Hibernate, JDO, and iBatis for the persistence tier. Spring lets you use a large variety of open-source tools behind the scenes, without needing large amounts of code or coupling the application too closely to the underlying frameworks.
Spring is also called a lightweight framework, since it replaces frameworks that are restrictive and cumbersome to use, such as EJB, that are already offered by JEE.
Spring is modularized with several components. Each component provides a particular service. The following sections summarize some of these.

Inversion of Control container

Inversion of Control (IoC) is the technology most identified with Spring. With the IoC core container, Spring enables the management of object dependencies by pushing dependencies into objects at runtime, instead of letting the objects pull their dependencies from their environment. This approach has many advantages:
  • All application classes are designed as simple as possible with minimum behaviors, and with their only required properties they will be well documented.
  • All application classes are self-documented, and the documentation is always up-to-date.
  • No class has its own configuration management, which allows more manageable code.
  • The application leaves configuration management to the framework.
  • IoC increases consistency in configuration management, since such management is accomplished by the framework.
  • The application has no need for any configuration management code since the framework handles this common aspect of every application.

Aspect-oriented programming framework

Aspect-oriented programming (AOP) is the perfect complementary approach to IoC, solving common problems related to J2EE design. AOP allows us to consolidate functionality, which would be otherwise scattered in different places, in a single place. Managing transactions is an example of this functionality. With Spring, transaction management occurs in a single place and is not scattered in persistence methods.
AOP complements object-oriented programming (OOP) by introducing a new concept, called concerns or aspects, to model real-world objects. Concerns are processes that are not directly related to the object hierarchy. Instead, they spread over sets of operations. For example, logging, security, and transaction are common examples for a concern, since they should be applied to sets of methods without any relationship to the object hierarchy.
Spring AOP has the following key benefits:
  • I t prevents code duplication and provides more manageable code.
  • It allows declarative enabling or disabling concerns.
Data access abstraction
Spring allows consistent data access to be implemented with solid abstraction. This is carried out through a rich hierarchy of exceptions and a set of helper classes, for working with a wide range of persistence technologies.

Transaction abstraction

Spring provides a transaction abstraction lay er over JTA (Jav a Transaction API) global transactions, which span multiple transactional resources. They are managed by an application server, or local transactions managed by JDBC, Hibernate, JDO, or any other persistence technology. It allows coding transactions, either programmatically or declaratively.

MVC web framework

Spring provides a rich, powerful web framework based on the Model-View-Controller (MVC) pattern. The aim of the framework, like any other web framework, is to simplify web development. It allows a variety of different view technologies, such as JavaServer Pages, Velocity, and iText PDF to be used. You can use MVC with Spring's other services, such as AOP and IoC. Furthermore, Spring can be integrated with other web frameworks, including Struts, WebWork, Tapestry, and JSF. Discussing Spring's web framework is beyond this article's scope. However, we will take a quick look at it, along with its alternatives, to give you a sense of how, in practice, Spring can be used to make web development easier and solve typical problems related to web applications.

Testing support

Spring applications are more readily testable than other applications. This is because Spring applications rely on POJOs, which do not call any Spring APIs, and their dependencies are normally expressed in the form of interfaces that are easy to stub or mock. Moreover, Spring provides some useful helper classes for implementing test classes that test an application's interaction with Spring.
Moreover, Spring provides a lightweight container against traditional full-blown JEE containers. The container provided by Spring can easily be started from the JUnit test itself, which is not easy to do with EJB-3 and a JEE container.

Summary

This article looked at Hibernate's background and explored how the framework provides a bridge between the object-oriented and relational worlds. This is why Hibernate is called an O/R mapping tool.
Enterprise JavaBeans are server-side components which provide another approach to persisting Java objects. In addition, enterprise beans provide declarative middleware services, such as transaction and security. Developing with enterprise beans is not as easy as developing with Hibernate, and using entity beans also requires an application server, which is difficult to set up, run, and test.
Hibernate architecture consists of three contributors: persistent objects, configuration file(s), and mapping definitions. The Hibernate API comes with three Java interfaces which are always involved in persisting the objects. These are org.hibernate.Session, org.hibernate.SessionFactory, and org.hibernate.Transaction.
If you have read this article you may be interested to view :
taken from "http://www.packtpub.com/article/introduction-to-hibernate-and-spring-1"

    An Introduction to Hibernate and Spring: Part 1


    This article introduces Spring and Hibernate, explaining what persistence is, why it is important, and how it is implemented in Java applications. It provides a theoretical discussion of Hibernate and how Hibernate solves problems related to persistence. Finally, we take a look at Spring and the role of Spring in persistence.
    Hibernate and Spring are open-source Java frameworks that simplify developing Java/JEE applications from simple, stand-alone applications running on a single JVM, to complex enterprise applications running on full-blown application servers. Hibernate and Spring allow developers to produce scalable, reliable, and effective code. Both frameworks support declarative configuration and work with a POJO (Plain Old Java Object) programming model (discussed later in this article), minimizing the dependence of application code on the frameworks, and making development more productive and portable.
    Although the aim of these frameworks partially overlap, for the most part, each is used for a different purpose. The Hibernate framework aims to solve the problems of managing data in Java: those problems which are not fully solved by the Java persistence API, JDBC (Java Database Connectivity), persistence providers, DBMS (Database Management Systems), and their mediator language, SQL (Structured Query Language).
    In contrast, Spring is a multitier framework that is not dedicated to a particular area of application architecture. However, Spring does not provide its own solution for issues such as persistence, for which there are already good solutions. Rather, Spring unifies preexisting solutions under its consistent API and makes them easier to use. As mentioned, one of these areas is persistence. Spring can be integrated with a persistence solution, such as Hibernate, to provide an abstraction layer over the persistence technology, and produce more portable, manageable, and effective code.
    Furthermore, Spring provides other services spread over the application architecture, such as inversion of control and aspect-oriented programming (explained later in this article), decoupling the application's components, and modularizing common behaviors.
    This article looks at the motivation and goals for Hibernate and Spring. The article begins with an explanation of why Hibernate is needed, where it can be used, and what it can do. We'll take a quick look at Hibernates alternatives, exploring their advantages and disadvantages. I'll outline the valuable features that Hibernate offers and explain how it can solve the problems of the traditional approach to Java persistence. The discussion continues with Spring. I'll explain what Spring is, what services it offers, and how it can help to develop a high-quality data-access layer with Hibernate.

    Persistence management in Java

    Persistence has long been a challenge in the enterprise community. Many persistence solutions from primitive, file-based approaches, to modern, object-oriented databases have been presented. For any of these approaches, the goal is to provide reliable, efficient, flexible, and scalable persistence.
    Among these competing solutions, relational databases (because of certain advantages) have been most widely accepted in the IT world. Today, almost all enterprise applications use relational databases. A relational database is an application that provides the persistence service. It provides many persistence features, such as indexing data to provide speedy searches; solves the relevant problems, such as protecting data from unauthorized access; and handles many complications, such as preserving relationships among data. Creating, modifying, and accessing relational databases is fairly simple. All such databases present data in two-dimensional tables and support SQL, which is relatively easy to learn and understand. Moreover, they provide other services, such as transactions and replication. These advantages are enough to ensure the popularity of relational databases.
    To provide support for relational databases in Java, the JDBC API was developed. JDBC allows Java applications to connect to relational databases, express their persistence purpose as SQL expressions, and transmit data to and from databases. The following screenshot shows how this works:
    Spring Persistence with Hibernate
    Using this API, SQL statements can be passed to the database, and the results can be returned to the application, all through a driver.

    The mismatch problem

    JDBC handles many persistence issues and problems in communicating with relational databases. It also provides the needed functionality for this purpose. However, there remains an unsolved problem in Java applications: Java applications are essentially object-oriented programs, whereas relational databases store data in a relational form. While applications use object-oriented forms of data, databases represent data in two-dimensional table forms. This situation leads to the so-called object-relational paradigm mismatch, which (as we will see later) causes many problems in communication between object-oriented and relational environments.
    For many reasons, including ease of understanding, simplicity of use, efficiency, robustness, and even popularity, we may not discard relational databases. However, the mismatch cannot be eliminated in an effortless and straightforward manner.

    Spring Persistence with Hibernate


    Build robust and reliable persistence solutions for your enterprise Java application
    • Get to grips with Hibernate and its configuration manager, mappings, types, session APIs, queries, and much more
    • Integrate Hibernate and Spring as part of your enterprise Java stack development
    • Work with Spring IoC (Inversion of Control), Spring AOP, transaction management, web development, and unit testing considerations and features
    • Covers advanced and useful features of Hibernate in a practical way

    Identity and equality mismatch

    The first and most significant mismatch involves the concepts of data equality. Java provides two definitions for object identity and equality. According to Java, two objects are called identical when they point to the same reference in memory. In contrast, two objects are considered equal when they contain similar data, as determined by the developer, regardless of the memory locations to which the objects point.
    Java offers the equals() method and == operator to support equality and identity, respectively. For instance, the == operator can be used as follows to check whether object1 and object2 are identical:
    object1==object2
    The equals() method, used as follows, determines whether two objects are equal:
    object1.equals(object2)
    When two objects are identical, they refer to the same memory location. Therefore, they have the same value and are definitely equal. However, two objects that are equal may not be identical since they may point to different locations in memory.
    The hashCode() method must be overridden in every class which overrides the equals() method. The hashCode() method returns an integer as the hash code value for the object on which this method is invoked. This code is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet, and so on. Equal objects must produce the same hash code, as long as they are equal. However, unequal objects do not need to produce distinct hash codes. See the JDK documentation for more details
    While Java offers two distinct definitions for object identity and equality, databases do not have any corresponding definitions for these terms. In a database, the data is represented as table rows, and each table row is identified based on the content it holds. A significant mismatch occurs when we map from the object-oriented world to the relational world. Although two objects are not identical because they refer to different locations in memory, in the database, they may be considered identical because they hold the same content.
    The common approach to eliminating this mismatch is to use an extra field in the object's class, and an extra identifier column in the respective table of the object. This approach identifies objects based on the identifier values they hold in either object or relational form, instead of identifying them based on their references in memory (in the object-oriented world) and based on the content they hold (and in the relational world). Therefore, as the following screenshot shows, each object and its corresponding row in the table can be identified through the same strategy, that is, by considering the identifier value:
    Let's look at a simple example. Suppose that our application has a Student class. We may typically use a STUDENT table in the database to store Student objects. We may also use an extra field in the class, called an object identifier, and a corresponding column in the table, called primary key, to allow objects to be recognized when they are stored, retrieved, or updated. The following screenshot shows the STUDENT table:
    Spring Persistence with Hibernate
    This table would hold the objects of the class shown in the following code listing. Note that, we have just shown the skeleton of the class with its properties and without its other details:
    package com.packtpub.springhibernate.ch01;
    
    import java.util.Date;
    
    public class Student {
      private int id;
      private String firstName;
      private String lastName;
      private String ssn;
      private Date birthdate;
      private String stdNo;
      private Date entranceDate ;
    
    
    }
    We may also use the following JDBC code in our application to store a Student object in the STUDENT table:
    Connection c = null;
    PreparedStatement p = null;
    
    try {
      Student std = ...//a ready to store Student object
      c = ...//obtaining a Connection object
      String q = "INSERT INTO STUDENT " + 
        "(ID, FIRST_NAME, LAST_NAME, SSN, BIRTHDATE, STD_NO, ENTRANCE_DATE)" + 
        " VALUES (?, ?, ?, ?, ?, ?, ?)";
      p = c.prepareStatement(q);
      p.setInt(1, std.getId());
      p.setString(2, std.getFirstName());
      p.setString(3, std.getLastName());
      p.setString(4, std.getSsn());
      p.setDate(5, new java.sql.Date(std.getBirthdate().getTime()));
      p.setString(6, std.getSsn());
      p.setDate(7, new java.sql.Date(std.getEntranceDate().getTime()));
    
      p.executeUpdate();
    } catch(Exception ex) {
      //handling the exception
    } finally {
      if (p != null) {
        try {
          p.close();
        } catch (SQLException e) {
          //handling the exception
        }
      }
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          //handling the exception
        }
      }
    }
    As you can see, to store a Student object, we need to obtain a PreparedStatement object with an appropriate SQL query. We then need to put the properties of the Student object in the PreparedStatement, and finally execute the update query by calling the executeUpdate() method of PreparedStatement. With all of these, we should handle exceptions when there is any problem in communicating to the database or executing the query.
    Similarly, we may use code such as the following to load a Student object
    Connection c = null;
    PreparedStatement p = null;
    Student std = null;
    
    try {
      int id = ...//the identifier of the student to  load
      c = ...//obtaining a Connection object
      String q = "SELECT FIRST_NAME, LAST_NAME, SSN, BIRTHDATE, 
      STD_NO, ENTRANCE_DATE " + "FROM STUDENT WHERE ID = ?";
      p = c.prepareStatement(q);
      p.setInt(1, id);
      ResultSet rs = p.executeQuery();
      if (rs.next()) {
        String firstName = rs.getString("FIRST_NAME");
        String lastName = rs.getString("LAST_NAME");
        String ssn = rs.getString("SSN"); 
        Date birthdate = rs.getDate("BIRTHDATE"); 
        String stdNo = rs.getString("STD_NO"); 
        Date entranceDate = rs.getDate("ENTRANCE_DATE"); 
        std = new Student(id, firstName, lastName, ssn, birthdate, stdNo, entranceDate);
        if (rs.next()) {
                //write a message warning about multiple objects
        }
      }   
    } catch(Exception ex) {
      //handling the exception
    } finally {
      if (p != null) {
        try {
          p.close();
        } catch (SQLException e) {
          //handling the exception
        }
      }
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          //handling the exception
        }
      }
    }
    return std;
    To load an object from the database, we need to obtain a PreparedStatment with an appropriate SQL query, set the required values, execute the query, iterate over the result, and produce the Student object. We should also handle the exceptions correspondingly.
    The most difficult and important parts of the above codes are the SQL statements. These statements are expressed in a different language than the language that object-oriented languages such as Java use. Besides, their syntax can't be checked in the compiled time since they are expressed in the raw String.
    As it can be concluded from both the previous examples, converting the object-oriented and relational forms of data to one another cannot be accomplished in an effortless and straightforward manner. After all, any change in the object model or the database schema can affect the converting code.
    This example demonstrates a primary difficulty in mapping objective and relational forms of data. However, this simple case requires only minimal effort to map a typical entity object. The mapping of objects could easily be more complicated than in the example, especially when an entity object is inherited from or associated with another object.

    Mapping object inheritance mismatch

    Another point where a mismatch occurs is in the mapping of object inheritance. While Java lets an object be inherited by another object, relational databases do not support the notion of inheritance. This means we need to define our own strategy to translate class hierarchy to database schema.
    Let's elaborate inheritance by extending our simple example using a general class, Person, as a superclass of Student. The class diagram shown in the following screenshot shows the Student class, which is now a subclass of Person:
    Spring Persistence with Hibernate
    The question here is, how can the object inheritance be persisted? Can it be persisted in one table? If not, how should we establish the relationship between tables?
    One solution would be to use individual tables for individual classes in the hierarchy. According to this solution, the objects of type superclass are stored directly in the superclass's table, but the subclass objects are persisted in both superclass and subclass tables. If we chose this strategy for our example, we would have two tables, PERSON and STUDENT, as shown in the following figure:
    Spring Persistence with Hibernate
    Because objects of the subclass are spread over two tables, we need a mechanism to recognize the association between rows when an object is retrieved, updated, or removed. Fortunately, many databases support foreign keys which are used to establish a relationship between database tables. This is what I have used in our example. As you can see, the STUDENT table takes the ID column as its primary key and a foreign key onto the PERSON table, meaning it holds the identifier of the associated row in the STUDENT table . When a Student object is stored, updated, or removed, the relevant student's data should be inserted in, updated in, or removed from the two tables. Moreover, to load a Student object, we need to query both tables with SQL joins, like this:
    Connection c = null;
    PreparedStatement p = null;
    Student std = null;
    try {
      int id =...//the identifier of the student that is loaded
      c = ...//obtaining a Connection object    
      c.setAutoCommit(false);
      String q = "SELECT P.FIRST_NAME, P.LAST_NAME, P.SSN, " +  
                 "P.BIRTHDATE, S.STD_NO, 
    S.ENTRANCE_DATE "+ 
                 "FROM PERSON P INNER JOIN STUDENT S " +
                 " ON P.ID = S.PERSON_ID WHERE P.ID=?; ";
      p = c.prepareStatement(q);
      p.setInt(1, id);
      ResultSet rs = p.executeQuery();
      if (rs.next()) {
        String firstName = rs.getString("FIRST_NAME");
        String lastName = rs.getString("LAST_NAME");
        String ssn = rs.getString("SSN");
        Date birthday = rs.getDate("BIRTHDATE");
        String stdNo = rs.getString("STD_NO");
        Date entranceDate = rs.getDate("ENTRANCE_DATE");
        std = new Student(id, firstName, lastName, ssn, 
                          birthday, stdNo, entranceDate);
        if (rs.next()) {
          //making a message warning about multiple objects existence
        }
      }
      p.close();
      c.commit();
    } catch (Exception ex) {
      //handling the exception
    } finally {
      if (p != null) {
        try {
          p.close();
        } catch (SQLException e) {
          //handling the exception
        }
      }
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          //handling the exception
        }
      }
    }
    return std;
    As you can see, using SQL joins makes the query expressions more complex, and consequently harder to develop, test, and maintain.

    Mapping more complicated objects

    Many Java objects are associated with other objects. The associated objects may be values or entities. Entities are objects that have their own persistent identity and are stored as discussed before. In contrast, values are objects that do not define some kind of persistent identity. If an entity object is associated with a value object, no real problem arises since the value object can be stored with the entity object in the same table. However, this is not true in the case of associations between two entity objects. Unfortunately, databases do not offer a way to persist object associations by default.
    The next mismatch happens when a graph of entity objects must be persisted in the database. In this case, the persistence should be accomplished in such a way that allows the object graph to be restored to its original form at a later time. As a common strategy, for each entity class a database table is used and when an object is stored, each object is persisted in its own database table. The next question here is, how can object associations be persisted? As with inheritance, foreign keys can be taken to establish inter-table relationships and provide table associations.
    Let's dig a bit deeper into object associations and extend our example to see how JDBC and SQL deal with associations in practice.

    Mapping a many-to-many association

    Let's assume that each student is associated with an array of courses. If each course is represented by another class, Course, then we have an object relationship like the one shown in the following screenshot:
    Spring Persistence with Hibernate
    The following code shows the Course class:
    package com.packtpub.springhibernate.ch01;
    
    public class Course {
      private int id;
      private String courseName;
      private int units;
    
      //setter and getter methods
    }
    And this shows the Student class:
    package com.packtpub.springhibernate.ch01;
    
    import java.util.Date;
    import java.util.List;
    
    public class Student extends Person {
      private String stdNo;
      private Date entranceDate;
      private List courses;
    
      //setter and getter methods
    }
    When we work with Hibernate, we always use simple classes which do not have any special behaviors. It is recommended that these classes be expressed with private properties and with setter and getter methods to access the properties.
    Note that, we have designed our classes as simple to be as possible to keep our example simple, as well. In this case, the COURSE table needs a foreign key column referring to the associated row in the STUDENT table. The tables may be related as shown in the following screenshot:
    Spring Persistence with Hibernate
    This kind of relationship indicates that when a Student object is persisted, the associated Course objects should be persisted as well. However, we may use a different strategy for updating or removing associated objects when the object is updated or removed. For example, we may decide that the associated objects are not to be updated when the object is updated, but they should be erased from the database when the object is removed. This is what we call a cascade operation, indicating whether the operation, or operations, should be propagated to associated entities.
    To load an entity object, we must query the appropriate table and any others associated with it. The following snippet shows the query to load a Student object with its associated courses:
    SELECT PERSON.FIRST_NAME, PERSON.LAST_NAME, PERSON.SSN,
    PERSON.BIRTHDATE, STUDENT.STD_NO, STUDENT.ENTRANCE_DATE,
    COURSE.ID, COURSE.COURSE_NAME, COURSE.UNITS FROM PERSON INNER
    JOIN (STUDENT INNER JOIN COURSE ON STUDENT.ID = 
    COURSE.STUDENT_ID) ON PERSON.ID = STUDENT.PERSON_ID WHERE 
    STUDENT.ID=?;
    It is very difficult, tedious, and error prone to use only pure JDBC and SQL to store the object graph in multiple tables, restore the object-oriented form of data, search object associations, and handle object inheritance. The SQL statements you use may not be optimized, and may be very difficult to test and maintain.
    This is the main reason to use a persistence framework such as Hibernate. The next section looks at Hibernate's background, as well as its advantages, alternatives, and architecture.









    Simple Introduction to Java Persistence



    Most applications involve creating, storing, and searching data in some form; in other words: use a database. This is often called CRUD, for Create, Read, Update, and Delete. Databases are integral parts of almost all computing systems. Well, I have a confession to make: I've been a professional software engineer for close to ten years now and I don't know anything about databases. Sure, I can write a simple SELECT call, but if you ask me to do an double outer join with foreign keys or convert my schema to 18th normal form, I'll simply get lost and give up. I don't know databases. In fact, I hate databases. I'm a client guy. To me, a database is simply a box to store stuff. I don't know how they work and I don't want to know. However, the sad fact of client software today is that as every application gets bigger, it eventually needs a database. From the largest billing system to something as simple as an address book, almost every application needs a database. But this doesn't change the fact that I still hate them. So what are we client developers to do? Here's a idea: why don't we steal some of the server guys' best technology to make our lives easier?

    Building on the new features in Java SE 5 (a.k.a. Tiger), the Java Enterprise Edition Enterprise Java Beans 3 spec (hereafter known by the blessedly shorter "EJB3") introduced a new way of communicating with databases called the Java Persistence API (JPA). Though primarily designed for use in big, server-based applications, I will show you how to use JPA to easily load, save, and search for data objects in a simple address book application. In a follow-up article, I will cover advanced object mapping, inheritance, and fetching. Most importantly, you will be able to do all of the database tasks without needing to know SQL, JDBC, or any other traditional database technologies. Let's hear it for the client side!

    What Are Java EE Persistence, Hibernate, and Hypersonic?


    Before we get into our application, let's take a moment to go over our tools: the Java Persistence API, Hibernate, and Hypersonic.

    EJB 3 introduced a new technology spec called the Java Persistence API, which defines a persistence framework. Persistence is a way of automatically mapping normal Java objects to an SQL database. In other words, it loads, searches, and saves your data model objects. Rather than writing cumbersome SQL insert, update, and select commands, the framework will take care of the boilerplate code through some kind of automation. The Java Persistence spec codifies the various persistence frameworks into a single API. This means you can write your application to the spec and know that it will work across several implementations, now and in the future.

    Hibernate is an open source implementation of the Java Persistence spec. Though it preceded JPA, and in fact influenced the final design, it has been retrofitted to implement the full spec (along with some extensions that I won't cover here). Hibernate is one of several implementations available, but I have chosen this one because it is complete, mature, and freely available. Much like JDBC, if you stick to the spec and don't use any of Hibernate's extensions, you will be able to switch implementations as your needs change in the future.

    HSQLDB, formerly "Hypersonic," is an open source SQL database that stores everything in a couple of files on disk. It has the advantages of being very small, easy to configure, and written entirely in Java. These features make it ideal to embed directly inside of your application: no database server required. Again, in this article we will stick to the database specs and not use any Hypersonic-specific features. This means you could upgrade to a full database server in the future if necessary.

    Building Your First Persistable Object


    In this article, we will build a simple address book application. The heart of any application is its data model. It is these objects that we want to create, save, and search. For an address book, I want to store people, so I have created the Person object below:

    package addressbook;
    import javax.persistence.*;
    
    @Entity
    public class Person {
        @Id @GeneratedValue
        public Long id;
        public String first;
        public String middle;
        public String last;
    }

    As you can see, this is a very simple class. It has three String fields for the first, middle, and last names, along with a Long for the ID. It looks like any normal Java object. In fact, the term most often used with persistence frameworks is POJO, or
    "Plain Old Java Object." The only things out of the ordinary for this object are the @Entity and @Id parts. Any symbol in Java code beginning with @ is known as an annotation. The use of annotations is a new language feature introduced in Java SE 5.0 that allows you to add metadata to your objects. Annotations mark parts of your objects so that other systems can do something special with them. In this article we will mark certain fields and classes with persistence annotations so that the Persistence framework will know how to save them.

    In the code above, the Person class is marked with the @Entity annotation, which means that it is an EJB entity. Being marked as an entity has a lot of ramifications, but for our purposes it just means that this object can be persisted. Any object you want to stuff in the database must be marked with the @Entity annotation. The @Id annotation says that the id field will be used as the unique identifier for this object. Databases use a special table column called a primary key to distinguish between rows. The @Id annotation marks the id field as the primary key for this object. The @GeneratedValue annotation tells the Persistence framework to generate IDs for us, which is fine, because we don't care what they are as long as they are unique. The @Id annotation has many optional parameters that let you further specify how your primary key works, such as selecting a particular column name or using multiple fields. For our needs, the default behavior is fine.

    You may notice that the other fields--first, middle, and last--don't have any annotations. That is because they are using the default annotations that say that the field is persistable as an SQL VARCHAR. As you explore the Java Persistence framework you will discover the JSR expert group did a very good job of defining defaults. This means that you only need to use non-default values when you want to do something out of the ordinary. This design choice, part of the overhaul in Java EE 5, makes persistence very easy to use for non-server developers.

    Setting Up Your Project


    Combining JPA, Hibernate, and Hypersonic requires a lot of .jars. If you want to build your own workspace, you must first go to the Hibernate website and download the Hibernate Core, Hibernate Annotations, and Hibernate Entity Manager .zip files. Be sure you download version 3.2cr2 or newer of the Hibernate Core file, because older versions won't work with annotations. Unpack them and put all of the .jars into your classpath (I typically put them in a lib subdirectory).

    There are a lot of .jars and not all of them are needed, depending on what you are doing, so I recommend using them all during development and then removing the ones you don't need when you get to deployment. The only one you should need in your compile-time classpath is ejb3-persistence.jar. The rest are for runtime use. Hibernate contains a lib/README.txt file with more details on the library requirements. You will also need the HSQLDB database in the form of the hsqldb.jar file.

    A quick note on library versions: the Hibernate Persistence implementation has been undergoing changes as the EJB 3 spec moves towards final ratification. Because of these changes, some versions of the Hibernate Core .jars don't work with some versions of the Annotations and Entity Manager .jars. When writing this series of articles, I found a few occasional NoSuchMethodErrors, indicating a version mismatch. I recommend downloading all versions of the modules that were released on the same day. For this article I used the versions released on March 27th, 2006. These are Hibernate Core v 3.2.0.cr1, Annotations v 3.1beta9, and Entity Manager v 3.1beta7. Until the changes settle down, I recommend staying with these versions. I have found them to work flawlessly.


    Now that you have a persistable object, the big question is: how do you persist it? This is where the EntityManager comes in. Each implementation of the Persistence API will have its own ways of connecting to a database and managing the objects, but as long as you don't use any implementation-specific extensions, you can stick to the official interfaces. The EntityManager keeps track of your objects and allows you to save, load, and search them at will. Like many Java APIs, Persistence uses a factory pattern, so that's where we will start. Here is a typical test application:

    package addressbook;
    import javax.persistence.*;
    
    public class Main {
        EntityManagerFactory factory;
        EntityManager manager;
       
        public void init() {
            factory = Persistence.createEntityManagerFactory("sample");
            manager = factory.createEntityManager();
        }

    To use persistence, you must first create an EntityManagerFactory using the static Persistence.createEntityManagerFactory() method. Notice the string "sample" passed to the method. This is the persistence unit you will be using, which must match the configuration in the persistence.xml file that we will get to later. Once you have a factory, you can get an EntityManager with the createEntityManager() method. In general, you should have one factory per application and one manager per user, usually handed out and managed by your application container. This is because the factory is thread-safe and the manager is not. However, these constraints were designed with web server applications in mind. For a desktop app where there is only person using it you can simply save the references and use them as you need. Just remember that the EntityManager isn't thread-safe, so be sure to do all of your persistence on the same thread or use multiple EntityManagers.

    Once you have finished your persistence operations you can shut down the manager and factory with their respective close methods.

        private void shutdown() {
            manager.close();
            factory.close();
        }
       
        public static void main(String[] args) {
            // TODO code application logic here
            Main main = new Main();
            main.init();
            try {
                // do some persistence stuff
            } catch (RuntimeException ex) {
                ex.printStackTrace();
            } finally {
                main.shutdown();
            }
        }
    }

    Above, you can see the main() method which creates a Main object, initializes the persistence system, does some work, and then calls shutdown() in a finally block. This simple Main class encapsulates the typical lifecycle of an application that uses persistence.

    Now that the persistence system is set up, we can finally persist some objects! You just need to create a transaction, create your objects, and then save them.

        private void create() {
            System.out.println("creating two people");
            EntityTransaction tx = manager.getTransaction();
            tx.begin();
            try {
                Person person = new Person();
                person.first = "Joshua";
                person.middle = "Michael";
                person.last = "Marinacci";
                manager.persist(person);
    
                Person sister = new Person();
                sister.first = "Rachel";
                sister.middle = "Suzanne";
                sister.last = "Hill";
                manager.persist(sister);
                tx.commit();
            } catch (Exception ex) {
                tx.rollback();
            }
            System.out.println("created two people");
        }

    Transactions are pretty much required with persistence because you are talking to a database underneath. You will usually create a transaction with manager.getTransaction(), call tx.begin(), and then do all of your work. The code above calls manager.persist() to save the new objects, but this could easily be calls to load, search, or update objects as well. Once finished you must call tx.commit() to make the changes permanent. Notice that the calls are wrapped in try/catch blocks. This is so you can rollback the transaction if anything goes wrong, leaving your database in a consistent state.

    Database Configuration


    There is one final piece of the puzzle before you can start saving objects. The entire persistence stack is configured with a persistence.xml file. This file lists the classes you want to persist, the database connection, and any properties that are specific to the Persistence implementation (Hibernate, in this case). Once you are set up, this XML file will be the only thing you need to modify if you change or move your database. This feature underlies the power of the Java Persistence API and makes the transition from developer database to big Oracle server quite easy. Here's what the persistence.xml file looks like:

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation=
       "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
       version="1.0">
    
       <persistence-unit name="sample" transaction-type="RESOURCE_LOCAL">
          <class>addressbook.Person</class>
    
          <properties>
             <property name="hibernate.connection.driver_class"
                value="org.hsqldb.jdbcDriver"/>
             <property name="hibernate.connection.username"
                value="sa"/>
             <property name="hibernate.connection.password"
                value=""/>
             <property name="hibernate.connection.url"
                value="jdbc:hsqldb:hsql://localhost"/>
             <property name="hibernate.dialect"
                value="org.hibernate.dialect.HSQLDialect"/>
             <property name="hibernate.hbm2ddl.auto"
                value="update"/>        
          </properties>
    
       </persistence-unit>
    </persistence>

    In the file above, the first thing you should notice is the name attribute of the persistence-unit element. It doesn't matter what this name is, as long as it matches the string passed into the Persistence.createEntityManagerFactory() method. Again, this API was designed to support advanced uses like multiple persistence stores and databases. Since this is uncommon for desktop apps, I recommend just using one name and never changing it. The persistence.xml file must be in the META-INF directory of your application .jar. If you are using NetBeans, you can put it in a META-INF directory of your src directory and let NetBeans copy it to the right place during compilation.

    Finally we are ready to crank up the database and start saving objects. Hypersonic is contained in a single .jar, hsqldb.jar, and you can start it with all of the default settings right from the command line.

    java -classpath lib/hsqldb.jar org.hsqldb.Server

    This will start an instance of Hypersonic on its default port with the database stored in the test.* files placed in the current working directory. Using the defaults is convenient for testing because you can remove the data by just deleting the created test.* files when you are done.

    If you compile and run the Main class, and have the database started in another window, then you should get a lot of output from Hibernate followed by the two lines:

    creating two people
    created two people

    Congratulations! You've just persisted your first objects. After you get the initial setup done, you'll discover how easy it is to store and retrieve your objects. You'll never need to write SQL again.

    Executing a Query


    Now that we can save our objects it would be nice to load them back up. You can do this with a simplified SQL-ish syntax called EJB3-QL. It lets you perform simple queries into the persistence store, much like SQL, except that instead of returning ResultSets, it will return Lists of your data objects. Below is a simple search function.

        private void search() {
            EntityTransaction tx = manager.getTransaction();
            tx.begin();
            System.out.println("searching for people");
            Query query = manager.createQuery("select p from Person p");
            List<Person> results = (List<Person>)query.getResultList();
            for(Person p : results) {
                System.out.println("got a person: " + p.first + " " + p.last);
            }
            System.out.println("done searching for people");
            tx.commit();
        }

    The query itself is generated by the manager.createQuery("select p from Person p") call. This is the simplest possible query. It will return all instances of the Person class. You could fully qualify the Person class as addressbook.Person, but this isn't necessary because the Persistence engine will use the unqualified classname by default. Once you have created a query, you can execute it with query.getResultList(). The code above places the query inside of a transaction, just like the create() method did earlier in this article.

    The EJB3-QL language is case-insensitive except for the Java class and method names, so select is equivalent to SeLeCt. It supports most of the usual SQL select features, such as where clauses. For example, if I wanted to search for just Persons with the first name of Joshua I could use the query: select p from Person p where p.first='Joshua'. The EJB3-QL language is powerful enough to perform most of the complicated things you could do with real SQL, like inner and outer joins, but I find that to be unnecessary for most client applications. I prefer to do simple where searches and then do any extra refinement in Java code.

    Starting the Database from Within Your Application


    Now that the program can load and save objects, it would be nice to have the database bundled with the application. We can't expect our users to manually start Hypersonic in another window. Fortunately Hypersonic was designed to run in-process, so this is quite easy.

    Before you create the EntityManager you must start Hypersonic by obtaining a database Connection object like this:

        public static void main(String[] args) throws Exception {
            // start hypersonic
            Class.forName("org.hsqldb.jdbcDriver").newInstance();
            Connection c = DriverManager.getConnection(
                    "jdbc:hsqldb:file:test", "sa", "");
            // start persistence
            Main main = new Main();
            main.init();
            // rest of the program....

    Then, just before your program ends, you must shut down Hypersonic with an SQL SHUTDOWN command like this:

            // shutdown hypersonic
            Statement stmt = c.createStatement();
            stmt.execute("SHUTDOWN");
            c.close();
        } // end main() method

    Also, since you have now changed the database configuration, you'll need to update your persistence.xml file, specifically changing the connection URL property from this:

    <property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost"/>

    to this:

    <property name="hibernate.connection.url" value="jdbc:hsqldb:test"/>

    With those few changes, the database will start up inside of your application, save all data to the test.* files, and shut down when your application ends. Hypersonic is a simple and compact way to store all of your application in a real database without your users ever knowing.

    Conclusion


    The Java Persistence API was designed as a simple way to load and save your data objects without using any SQL at all. Since it was also designed to be implementation independent, you can change your database or persistence provider as your needs change and not worry about anything breaking. Though Java Persistence was originally designed for server tasks, it performs beautifully in client applications, letting client-side developers spend less time on storage and more time on what they are good at: building killer GUIs.

    Join me in a few weeks a follow-up article in which we explore advanced persistence features like constraints, customized properties, subclasses, and managing entire graphs of objects at once.

    Resources

    taken from "http://today.java.net/article/2006/05/19/introduction-java-persistence-client-side-developers"

    What is EJB 3.0

    This lesson introduces you with EJB 3.0, which is being used extensively for developement of robust, scalable and secure applications.

    What is EJB?
    The Enterprise JavaBeans architecture or EJB for short is an architecture for the development
    and deployment of component-based robust, highly scalable business applications.
    These Applications are scalable, transactional, and multi-user secure. You can
    develop the application once and then deploy on any one of the JEE 5 complaint
    application server. There are many application servers are available both free
    and commercial. You can choose the server for development and deployment to suit
    your requirement and budget.
    Benefits of EJB
    EJB simplifies the development of small and large enterprise applications.
    The EJB container provides system-level services to enterprise beans, the bean developer can
    just concentrate on developing logic to solve business problems.
    Types of EJB
    1. Session Bean

      Session is one of  the EJBs and it  represents a single client
      inside the Application Server. Stateless session is easy to develop and its
      efficient. As compare to entity beans session beans require few server
      resources.

      A session bean is similar to an interactive session and is not shared; it
      can have only one client, in the same way that an interactive session can
      have only one user. A session bean is not persistent and it is destroyed
      once the session terminates.

      Session Bean Types

      Session Beans are of two types, Stateful Session Bean and Stateless Session
      Bean.

      Stateless Session Beans

      A stateless session bean does not maintain a conversational state for
      the client. When a client invokes the method of a stateless bean, the bean's
      instance variables may contain a state, but only for the duration of the
      invocation.

      Because stateless session beans can support multiple clients, they can offer
      better scalability for applications that require large numbers of clients.
      Typically, an application requires fewer stateless session beans than
      stateful session beans to support the same number of clients.

      Stateful Session Beans

      The state of an object consists of the values of its instance variables.
      In a stateful session bean, the instance variables represent the state of a
      unique client-bean session. Because the client interacts ("talks")
      with its bean, this state is often called the conversational state.

        
    2. Entity Bean

      Enity beans are persistence java objects, whose state can be saved into the
      database and later can it can be restored from Data store. Entity bean
      represents a row of the database table.

        
    3. Message Driven Bean

      Message Driven Bean is an enterprise bean that can be used by JEE
      applications to process the messages asynchronously. Message Driven Bean
      acts as message consumer and it receives JMS messages.
    EJB 3.0 New Features
    Following are the new features of EJB 3.0:
    1. Metadata Annotations

      EJB 3.0 extensively uses the metadata annotations to simplify the development
      of EJB 3.0 components. Now there is no need to write the deployment
      descriptor, but the deployment descriptor is still supported. Annotations
      can be overridden by deployment descriptor.
        
    2. Encapsulation of environmental dependencies

      EJB 3.0 now uses the annotations and dependency injection mechanism to
      encapsulation the environmental dependencies and JNDI access.
        
    3. More simplified EJB Specification

      EJB 3.0 is simplified Specification but still very powerful. Now there is no
      need to write home and component interfaces and implementing the javax.ejb.EnterpriseBean
      interface by EJB class. The EJB bean class is now pure java class, also know
      as POJO and the interface is know as POJI is simple Java interface. So, you
      can now developed your enterprise application very fast.
        
    4. Dependency Injection

      Now the API for lookup and usage of EJB environment and resource references
      has been simplified and dependency injection is used through metadata
      annotations.
        
    5. Simplification of Entity Persistence

      Persistence of the entity objects are now very simple through the
      introduction of Java Persistence API. A new API EntityManager API
      has been introduced is used create, find, remove and update entities. Now
      the domain objects supports inheritance and polymorphism.
        
    6. Callback interfaces
      Elimination of the requirement for the implementation of callback interfaces.
    taken from "http://www.roseindia.net/java/jee5/what-is-ejb3.shtml"

      Monday, December 13, 2010

      What does Spring do?

      Spring provides a lot of functionality, so I'll quickly review each major area
      in turn.

      Mission statement
      Firstly, let's be clear on Spring's scope. Although Spring covers a lot of
      ground, we have a clear vision as to what it should and shouldn't address.

      Spring's main aim is to make J2EE easier to use and promote good programming
      practice. It does this by enabling a POJO-based programming model that is
      applicable in a wide range of environments.

      Spring does not reinvent the wheel. Thus you'll find no logging
      packages in Spring, no connection pools, no distributed transaction
      coordinator. All these things are provided by open source projects (such as
      Commons Logging, which we use for all our log output, or Commons DBCP), or by
      your application server. For the same reason, we don't provide an O/R mapping
      layer. There are good solutions to this problem such as TopLink, Hibernate and
      JDO.

      Spring does aim to make existing technologies easier to use. For example,
      although we are not in the business of low-level transaction coordination, we
      do provide an abstraction layer over JTA or any other transaction strategy.

      Spring doesn't directly compete with other open source projects unless we feel
      we can provide something new. For example, like many developers, we have never
      been happy with Struts, and felt that there was room for improvement in MVC
      web frameworks. (With Spring MVC adoption growing rapidly, it seems that many
      agree with us.) In some areas, such as its lightweight IoC container and AOP
      framework, Spring does have direct competition, but Spring was a pioneer in
      those areas.

      Spring benefits from internal consistency. All the developers are singing from
      the same hymn sheet, the fundamental ideas remaining faithful to those of
      Expert One-on-One J2EE Design and Development. And we've been able to
      use some central concepts, such as Inversion of Control, across multiple
      areas.

      Spring is portable between application servers. Of course ensuring portability
      is always a challenge, but we avoid anything platform-specific or non-standard
      in the developer's view, and support users on WebLogic, Tomcat, Resin, JBoss,
      Jetty, Geronimo, WebSphere and other application servers. Spring's
      non-invasive, POJO, approach enables us to take advantage of
      environment-specific features without sacrificing portability, as in the case
      of enhanced WebLogic transaction management functionality in Spring 1.2 that
      uses BEA proprietary APIs under the covers.

      Inversion of control container
      The core of Spring is the org.springframework.beans package, designed for working with JavaBeans.
      This package typically isn't used directly by users, but underpins much Spring
      functionality.

      The next higher layer of abstraction is the bean factory. A Spring bean
      factory is a generic factory that enables objects to be retrieved by name, and
      which can manage relationships between objects.

      Bean factories support two modes of object:

      • Singleton: in this case, there's one shared instance of the object
        with a particular name, which will be retrieved on lookup. This is the
        default, and most often used, mode. It's ideal for stateless service
        objects.
      • Prototype or non-singleton: in this case, each retrieval will result
        in the creation of an independent object. For example, this could be used to
        allow each caller to have its own distinct object reference.
      Because the Spring container manages relationships between objects, it can add
      value where necessary through services such as transparent pooling for managed
      POJOs, and support for hot swapping, where the container introduces a level of
      indirection that allows the target of a reference to be swapped at runtime
      without affecting callers and without loss of thread safety. One of the
      beauties of Dependency Injection (discussed shortly) is that all this is
      possible transparently, with no API involved.

      As org.springframework.beans.factory.BeanFactory is a simple interface, it can be implemented in different ways. The BeanDefinitionReader
      interface separates the metadata format from BeanFactory implementations themselves,
      so the generic BeanFactory implementations Spring provides can be used with different
      types of metadata. You could easily implement your own BeanFactory or
      BeanDefinitionReader, although few users find a need to. The most commonly
      used BeanFactory definitions are:

      • XmlBeanFactory. This parses a simple, intuitive XML structure defining the classes and
        properties of named objects. We provide a DTD to make authoring easier.
      • DefaultListableBeanFactory: This provides the ability to parse bean definitions in properties
        files, and create BeanFactories programmatically.
      Each bean definition can be a POJO (defined by class name and JavaBean
      initialisation properties or constructor arguments), or a FactoryBean. The FactoryBean
      interface adds a level of indirection. Typically this is used to create
      proxied objects using AOP or other approaches: for example, proxies that add
      declarative transaction management. This is conceptually similar to EJB
      interception, but works out much simpler in practice, and is more powerful.

      BeanFactories can optionally participate in a hierarchy, "inheriting"
      definitions from their ancestors. This enables the sharing of common
      configuration across a whole application, while individual resources such as
      controller servlets also have their own independent set of objects.

      This motivation for the use of JavaBeans is described in Chapter 4 of
      Expert One-on-One J2EE Design and Development, which is available on
      the ServerSide as a free PDF
      (/articles/article.tss?l=RodJohnsonInterview).

      Through its bean factory concept, Spring is an Inversion of Control
      container. (I don't much like the term container, as it conjures up
      visions of heavyweight containers such as EJB containers. A Spring BeanFactory
      is a container that can be created in a single line of code, and requires no
      special deployment steps.) Spring is most closely identified with a flavor of
      Inversion of Control known as Dependency Injection--a name coined by
      Martin Fowler, Rod Johnson and the PicoContainer team in late 2003.

      The concept behind Inversion of Control is often expressed in the Hollywood
      Principle
      : "Don't call me, I'll call you." IoC moves the responsibility
      for making things happen into the framework, and away from application code.
      Whereas your code calls a traditional class library, an IoC framework calls
      your code. Lifecycle callbacks in many APIs, such as the setSessionContext() method for
      session EJBs, demonstrate this approach.

      Dependency Injection is a form of IoC that removes explicit dependence on
      container APIs; ordinary Java methods are used to inject dependencies
      such as collaborating objects or configuration values into application object
      instances. Where configuration is concerned this means that while in
      traditional container architectures such as EJB, a component might call the
      container to say "where's object X, which I need to do my work", with
      Dependency Injection the container figures out that the component needs
      an X object, and provides it to it at runtime. The container does this
      figuring out based on method signatures (usually JavaBean properties or
      constructors) and, possibly, configuration data such as XML.

      The two major flavors of Dependency Injection are Setter Injection
      (injection via JavaBean setters); and Constructor Injection (injection
      via constructor arguments). Spring provides sophisticated support for both,
      and even allows you to mix the two when configuring the one object.

      As well as supporting all forms of Dependency Injection, Spring also provides
      a range of callback events, and an API for traditional lookup where necessary.
      However, we recommend a pure Dependency Injection approach in general.

      Dependency Injection has several important benefits. For example:

      • Because components don't need to look up collaborators at runtime, they're
        much simpler to write and maintain. In Spring's version of IoC, components
        express their dependency on other components via exposing JavaBean setter
        methods or through constructor arguments. The EJB equivalent would be a JNDI
        lookup, which requires the developer to write code that makes environmental
        assumptions.
      • For the same reasons, application code is much easier to test. For example,
        JavaBean properties are simple, core Java and easy to test: simply write a
        self-contained JUnit test method that creates the object and sets the
        relevant properties.
      • A good IoC implementation preserves strong typing. If you need to use a
        generic factory to look up collaborators, you have to cast the results to
        the desired type. This isn't a major problem, but it is inelegant. With IoC
        you express strongly typed dependencies in your code and the framework is
        responsible for type casts. This means that type mismatches will be raised
        as errors when the framework configures the application; you don't have to
        worry about class cast exceptions in your code.
      • Dependencies are explicit. For example, if an application class tries to
        load a properties file or connect to a database on instantiation, the
        environmental assumptions may not be obvious without reading the code
        (complicating testing and reducing deployment flexibility). With a
        Dependency Injection approach, dependencies are explicit, and evident in
        constructor or JavaBean properties.
      • Most business objects don't depend on IoC container APIs. This makes it easy
        to use legacy code, and easy to use objects either inside or outside the IoC
        container. For example, Spring users often configure the Jakarta Commons
        DBCP DataSource as a Spring bean: there's no need to write any custom code
        to do this. We say that an IoC container isn't invasive: using it
        won't invade your code with dependency on its APIs. Almost any POJO can
        become a component in a Spring bean factory. Existing JavaBeans or objects
        with multi-argument constructors work particularly well, but Spring also
        provides unique support for instantiating objects from static factory
        methods or even methods on other objects managed by the IoC container.
      This last point deserves emphasis. Dependency Injection is unlike traditional
      container architectures, such as EJB, in this minimization of dependency of
      application code on container. This means that your business objects can
      potentially be run in different Dependency Injection frameworks - or outside
      any framework - without code changes.

      In my experience and that of Spring users, it's hard to overemphasize the
      benefits that IoC--and, especially, Dependency Injection--brings to
      application code.

      Dependency Injection is not a new concept, although it's only recently made
      prime time in the J2EE community. There are alternative DI containers:
      notably, PicoContainer and HiveMind. PicoContainer is particularly lightweight
      and emphasizes the expression of dependencies through constructors rather than
      JavaBean properties. It does not use metadata outside Java code, which limits
      its functionality in comparison with Spring. HiveMind is conceptually more
      similar to Spring (also aiming at more than just IoC), although it lacks the
      comprehensive scope of the Spring project or the same scale of user community.
      EJB 3.0 will provide a basic DI capability as well.

      Spring BeanFactories are very lightweight. Users have successfully used them
      inside applets, as well as standalone Swing applications. (They also work fine
      within an EJB container.) There are no special deployment steps and no
      detectable startup time associated with the container itself (although certain
      objects configured by the container may of course take time to initialize).
      This ability to instantiate a container almost instantly in any tier of an
      application can be very valuable.

      The Spring BeanFactory concept is used throughout Spring, and is a key reason
      that Spring is so internally consistent. Spring is also unique among IoC
      containers in that it uses IoC as a basic concept throughout a full-featured
      framework.

      Most importantly for application developers, one or more BeanFactories provide
      a well-defined layer of business objects. This is analogous to, but much
      simpler (yet more powerful), than a layer of local session beans. Unlike EJBs,
      the objects in this layer can be interrelated, and their relationships managed
      by the owning factory. Having a well-defined layer of business objects is very
      important to a successful architecture.

      A Spring ApplicationContext is a subinterface of BeanFactory, which provides
      support for:

      • Message lookup, supporting internationalization
      • An eventing mechanism, allowing application objects to publish and
        optionally register to be notified of events
      • Automatic recognition of special application-specific or generic bean
        definitions that customize container behavior
      • Portable file and resource access
      XmlBeanFactory example
      Spring users normally configure their applications in XML "bean definition"
      files. The root of a Spring XML bean definition document is a <beans> element. The
      <beans> element contains one or more <bean> definitions. We normally specify the
      class and properties of each bean definition. We must also specify the id,
      which will be the name that we'll use this bean with in our code.

      Let's look at a simple example, which configures three application objects
      with relationships commonly seen in J2EE applications:

      • A J2EE DataSource
      • A DAO that uses the DataSource
      • A business object that uses the DAO in the course of its work
      In the following example, we use a BasicDataSource from the Jakarta Commons DBCP project.
      (ComboPooledDataSource from the C3PO project is also an excellent option.) BasicDataSource, like many other
      existing classes, can easily be used in a Spring bean factory, as it offers
      JavaBean-style configuration. The close method that needs to be called on
      shutdown can be registered via Spring's "destroy-method" attribute, to avoid
      the need for BasicDataSource to implement any Spring interface.

      <beans>
      
        <bean id="myDataSource"
       class="org.apache.commons.dbcp.BasicDataSource"
       destroy-method="close">
          <property name="driverClassName" value="com.mysql.jdbc.Driver" />
          <property name="url" value="jdbc:mysql://localhost:3306/mydb" />
          <property name="username" value="someone" />
        </bean>
      All the properties of BasicDataSource we're interested in are Strings, so we specify their
      values with the "value" attribute. (This shortcut was introduced in Spring
      1.2. It's a convenient alternative to the <value> subelement, which is usable even
      for values that are problematic in XML attributes.) Spring uses the standard
      JavaBean PropertyEditor mechanism to convert String representations to other
      types if necessary.

      Now we define the DAO, which has a bean reference to the DataSource.
      Relationships between beans are specified using the "ref" attribute or <ref>
      element:

      <bean id="exampleDataAccessObject"
        class="example.ExampleDataAccessObject">
          <property name="dataSource" ref="myDataSource" />
        </bean>
      The business object has a reference to the DAO, and an int property
      (exampleParam). In this case, I've used the subelement syntax familiar to
      those who've used Spring prior to 1.2:

      <bean id="exampleBusinessObject"
        class="example.ExampleBusinessObject">
          <property name="dataAccessObject"><ref bean="exampleDataAccessObject"/></property>
          <property name="exampleParam"><value>10</value></property>
        </bean>
      
      </beans>
      Relationships between objects are normally set explicitly in configuration, as
      in this example. We consider this to be a Good Thing in most cases. However,
      Spring also provides what we call "autowire" support, where it figures out the
      dependencies between beans. The limitation with this - as with PicoContainer -
      is that if there are multiple beans of a particular type it's impossible to
      work out which instance a dependency of that type should be resolved to. On
      the positive side, unsatisfied dependencies can be caught when the factory is
      initialized. (Spring also offers an optional dependency check for explicit
      configuration, which can achieve this goal.)

      We could use the autowire feature as follows in the above example, if we
      didn't want to code these relationships explicitly:

      <bean id="exampleBusinessObject"
       class="example.ExampleBusinessObject"
       autowire="byType">
      
          <property name="exampleParam" value="10" />
       </bean>
      With this usage, Spring will work out that the dataSource property of
      exampleBusinessObject should be set to the implementation of DataSource it
      finds in the present BeanFactory. It's an error if there is none, or more than
      one, bean of the required type in the present BeanFactory. We still need to
      set the exampleParam property, as it's not a reference.

      Autowire support has the advantage of reducing the volume of configuration. It
      also means that the container can learn about application structure using
      reflection, so if you add an additional constructor argument of JavaBean
      property, it may be successfully populated without any need to change
      configuration. The tradeoffs around autowiring need to be evaluated carefully.

      Externalizing relationships from Java code has an enormous benefit over hard
      coding it, as it's possible to change the XML file without changing a line of
      Java code. For example, we could simply change the myDataSource bean definition to
      refer to a different bean class to use an alternative connection pool, or a
      test data source. We could use Spring's JNDI location FactoryBean to get a
      datasource from an application server in a single alternative XML stanza, as
      follows. There would be no impact on Java code or any other bean definitions.

      <bean id="myDataSource"
       class="org.springframework.jndi.JndiObjectFactoryBean">
          <property name="jndiName" value="jdbc/myDataSource" />
        </bean>
      Now let's look at the Java code for the example business object. Note that
      there are no Spring dependencies in the code listing below. Unlike an EJB
      container, a Spring BeanFactory is not invasive: you don't normally need to
      code awareness of it into application objects.

      public class ExampleBusinessObject implements MyBusinessObject {
      
       private ExampleDataAccessObject dao;
       private int exampleParam;
      
       public void setDataAccessObject(ExampleDataAccessObject dao) {
        this.dao = dao;
       }
      
       public void setExampleParam(int exampleParam) {
        this.exampleParam = exampleParam;
       }
      
       public void myBusinessMethod() {
        // do stuff using dao
       }
      }
      Note the property setters, which correspond to the XML references in the bean
      definition document. These are invoked by Spring before the object is used.

      Such application beans do not need to depend on Spring: They don't need to
      implement any Spring interfaces or extend Spring classes: they just need to
      observe JavaBeans naming convention. Reusing one outside of a Spring
      application context is easy, for example in a test environment. Just
      instantiate it with its default constructor, and set its properties manually,
      via setDataSource() and setExampleParam() calls. So long as you have a no-args constructor, you're free
      to define other constructors taking multiple properties if you want to support
      programmatic construction in a single line of code.

      Note that the JavaBean properties are not declared on the business interface
      callers will work with. They're an implementation detail. We can easily "plug
      in" different implementing classes that have different bean properties without
      affecting connected objects or calling code.

      Of course Spring XML bean factories have many more capabilities than described
      here, but this should give you a feel for the basic approach. As well as
      simple properties, and properties for which you have a JavaBeans
      PropertyEditor, Spring can handle lists, maps and java.util.Properties. Other advanced
      container capabilities include:


      • Inner beans, in which a property element contains an anonymous bean
        definition not visible at top-level scope

      • Post processors: special bean definitions that customize container
        behavior

      • Method Injection, a form of IoC in which the container implements an
        abstract method or overrides a concrete method to inject a dependency. This
        is a more rarely used form of Dependency Injection than Setter or
        Constructor Injection. However, it can be useful to avoid an explicit
        container dependency when looking up a new object instance for each
        invocation, or to allow configuration to vary over time--for example, with
        the method implementation being backed by a SQL query in one environment and
        a fil system read in another.
      Bean factories and application contexts are often associated with a scope
      defined by the J2EE server or web container, such as:


      • The Servlet context. In the Spring MVC framework, an application context is
        defined for each web application containing common objects. Spring provides
        the ability to instantiate such a context through a listener or servlet
        without dependence on the Spring MVC framework, so it can also be used in
        Struts, WebWork or other web frameworks.

      • A Servlet: Each controller servlet in the Spring MVC framework has its own
        application context, derived from the root (application-wide) application
        context. It's also easy to accomplish this with Struts or another MVC
        framework.

      • EJB: Spring provides convenience superclasses for EJB that simplify EJB
        authoring and provide a BeanFactory loaded from an XML document in the EJB
        Jar file.
      These hooks provided by the J2EE specification generally avoid the need to use
      a Singleton to bootstrap a bean factory.

      However, it's trivial to instantiate a BeanFactory programmatically if we
      wish. For example, we could create the bean factory and get a reference to the
      business object defined above in the following three lines of code:

      XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("myFile.xml", getClass()));
      MyBusinessObject mbo = (MyBusinessObject) bf.getBean("exampleBusinessObject");
      This code will work outside an application server: it doesn't even depend on
      J2EE, as the Spring IoC container is pure Java. The Spring Rich project
      (a framework for simplifying the development of Swing applications using
      Spring) demonstrates how Spring can be used outside a J2EE environment, as do
      Spring's integration testing features, discussed later in this article.
      Dependency Injection and the related functionality is too general and valuable
      to be confined to a J2EE, or server-side, environment.