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();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Student student = ...//a new instantiated student object
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();;
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.


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 ""

    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:
    The equals() method, used as follows, determines whether two objects are equal:
    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 " + 
        " 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()));
    } catch(Exception ex) {
      //handling the exception
    } finally {
      if (p != null) {
        try {
        } catch (SQLException e) {
          //handling the exception
      if (c != null) {
        try {
        } 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
      p = c.prepareStatement(q);
      p.setInt(1, id);
      ResultSet rs = p.executeQuery();
      if ( {
        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 ( {
                //write a message warning about multiple objects
    } catch(Exception ex) {
      //handling the exception
    } finally {
      if (p != null) {
        try {
        } catch (SQLException e) {
          //handling the exception
      if (c != null) {
        try {
        } 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    
      String q = "SELECT P.FIRST_NAME, P.LAST_NAME, P.SSN, " +  
                 "P.BIRTHDATE, S.STD_NO, 
                 "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 ( {
        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 ( {
          //making a message warning about multiple objects existence
    } catch (Exception ex) {
      //handling the exception
    } finally {
      if (p != null) {
        try {
        } catch (SQLException e) {
          //handling the exception
      if (c != null) {
        try {
        } 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:
    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.*;
    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() {
        public static void main(String[] args) {
            // TODO code application logic here
            Main main = new Main();
            try {
                // do some persistence stuff
            } catch (RuntimeException ex) {
            } finally {

    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();
            try {
                Person person = new Person();
                person.first = "Joshua";
                person.middle = "Michael";
                person.last = "Marinacci";
                Person sister = new Person();
                sister.first = "Rachel";
                sister.middle = "Suzanne";
                sister.last = "Hill";
            } catch (Exception ex) {
            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=""
       <persistence-unit name="sample" transaction-type="RESOURCE_LOCAL">
             <property name="hibernate.connection.driver_class"
             <property name="hibernate.connection.username"
             <property name="hibernate.connection.password"
             <property name="hibernate.connection.url"
             <property name="hibernate.dialect"
             <property name=""

    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();
            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");

    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
            Connection c = DriverManager.getConnection(
                    "jdbc:hsqldb:file:test", "sa", "");
            // start persistence
            Main main = new Main();
            // 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();
        } // 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.


    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.


    taken from ""

    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

      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

      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

      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
    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 ""