Flylib.com

Books Software

 
 
 

Section 5.7. Hibernate Checklist


5.7. Hibernate Checklist

Before we get to the actual HibernateCarDAO , let's recap what we've done up to this point. We:

  • Added Hibernate tags to the CarDTO and created an Ant task to create the Mapping File ( cardto.hbm.xml )

  • Created a Hibernate MBean service descriptor ( hibernate-service.xml )

  • Bundled these two files up in a HAR ( common/build/distribution/jaw.har )

  • Created a jboss-app.xml file so JBoss would know how to deploy the HAR included in the EAR

  • Created a global JNDI reference to the Session Factory in jboss-web.xml ( java:/hibernate/SessionFactory )

  • Created a local JNDI reference to the Session Factory in web.xml conforming to the J2EE ENC naming style ( java:comp/env/hibernate/SessionFactory )

  • Modified the ServiceLocator class that encapsulates all JNDI lookups to return a Hibernate Session

JBoss 4.0.2 and Hibernate 3.0.2 Issues

Bugs are facts of life. Even though JBoss and Hibernate are excellent products, JBoss 4.0.2 and Hibernate 3.0.2 straight out of the box have one significant problema core JAR file that inadvertently was left out of the distribution. The Apache Jakarta Commons Collections JAR needs to be downloaded separately and installed for Hibernate to work correctly. Visit the website (http://jakarta.apache.org/site/downloads/downloads_commons-collections.cgi) and download Version 2.1.1 of the JAR. Then copy it to one of the following directories:

  • $JBOSS_HOME/server/default/lib

  • $JBOSS_HOME/server/default/deploy/jboss-hibernate.deployer

This issue should be resolved in JBoss 4.0.3.




5.8. HibernateCarDAO

It's taken a while to get here, but now that the infrastructure is in place, we can get to the whole point of this chapterseeing Hibernate in action. In JDBCCarDAO , we performed the SQL query and manually marshaled the ResultSet rows into CarDTO objects.

Example 5-13 shows what the JDBC code looks like.

Example 5-13. JDBCCarDAO.java
private static final String DATA_SOURCE="java:comp/env/jdbc/JBossAtWorkDS";

    public List findAll(  )
    {
        List carList = new ArrayList(  );
        DataSource dataSource = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try
        {
            dataSource = ServiceLocator.getDataSource(DATA_SOURCE);
            conn = dataSource.getConnection(  );
            stmt = conn.createStatement(  );
            rs = stmt.executeQuery("select * from CAR");

            while(rs.next(  ))
            {
                CarDTO car = new CarDTO(  );
                car.setId(rs.getInt("ID"));
                car.setMake(rs.getString("MAKE"));
                car.setModel(rs.getString("MODEL"));
                car.setModelYear(rs.getString("MODEL_YEAR"));
                carList.add(car);
            }

        }
        catch (Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            try
            {
                if(rs != null){rs.close(  );}
                if(stmt != null){stmt.close(  );}
                if(conn != null){conn.close(  );}
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }

        return carList;
    }

It's nearly 50 lines of code, if you include all the exception handling. The point of showing this to you is to remind you that we do all the work by hand.

Now let's see the same method implemented with Hibernate in Example 5-14.

Example 5-14. HibernateCarDAO.java
private static final String
 HIBERNATE_SESSION_FACTORY="java:comp/env/hibernate/SessionFactory";

    public List findAll(  )
    {
        List carList = new ArrayList(  );
        Session session = null;

        try
        {
            session = ServiceLocator.getHibernateSession(HIBERNATE_SESSION_FACTORY);
            Criteria criteria = session.createCriteria(CarDTO.class);
            carList = criteria.list(  );
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            try
            {
                if (session != null) {session.close(  );}
            }
            catch (Exception e)
            {
                System.out.println(e);
            }
        }

        return carList;
    }

It is far more compactwith a nearly 50% reduction in total lines of code. More importantly, the code doing the real work was reduced to three steps:

  1. Acquire a Hibernate session

  2. Create a Criteria object. This line is the Hibernate equivalent of saying " select * from CAR ".

  3. Get the resulting carList from the query.

The ResultSet row marshalling still happens, but the Hibernate API takes care of it behind the scenes. Our code is lean and clean.

We'll explore some more in depth Hibernate examples in just a bit, and will cover the full CRUD spectrum (Create, Read, Update, and Delete). But for now, let's change our ControllerServlet and deploy the application.

To begin using HibernateCarDAO , all we need to do is change how the CarDAO interface is instantiated in ControllerServlet (Example 5-15).

Example 5-15. ControllerServlet.java
if(VIEW_CAR_LIST_ACTION.equals(actionName))
        {
            CarDAO carDAO = new HibernateCarDAO(  );
            request.setAttribute("carList", carDAO.findAll(  ));
            destinationPage = "/carList.jsp";
        }

Now that everything is in place, let's build and deploy the application:

  1. Type ant in the root directory of 05a-list to build the project.

  2. Shut down JBoss.

  3. Type ant colddeploy .

  4. Start JBoss back up.

  5. Visit http://localhost:8080/jaw in a web browser.

Click on the View Inventory link to see Figure 5-1.

Figure 5-1. viewCarList using Hibernate

OK, so we've been through at least five distinct iterations that have all given us the same result:

  • Using scriptlet code to generate the carList

  • Using the ControllerServlet to generate the carList

  • Using the InMemoryCarDAO to generate the carList

  • Using the JDBCCarDAO to generate the carList

  • Using the HibernateCarDAO to generate the carList

In each case, the view remained constantonly the back-end services have gotten progressively more sophisticated. For sticking with us this long, we'll reward you with some new functionality. Let's flesh out this example by allowing the user to add new cars, edit existing cars, and delete cars from the list. This will allow us to run Hibernate through its paces.