Java
  Home arrow Java arrow Page 2 - Adding Hibernate to a Java Application
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Adding Hibernate to a Java Application
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2006-11-30

    Table of Contents:
  • Adding Hibernate to a Java Application
  • Hibernate Mappings for Existing Domain Objects
  • Changing the Application Configuration
  • Spring’s Built-In Hibernate Support

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Adding Hibernate to a Java Application - Hibernate Mappings for Existing Domain Objects


    (Page 2 of 4 )

    To replace this architecture with one based on Hibernate, we first have to create mapping files that define the relationship between the domain objects and the database. Looking again at Product, we’ll create a mapping file called Product.hbm.xml which looks like:

      <?xml version="1.0"?>
      <!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
          "http://hibernate.sourceforge.net/ hibernate-mapping-2.0.dtd">

      <hibernate-mapping 
          package="org.springframework.samples. ipetstore.domain">

          <class name="Product" table="product">
            
    <id name="productId"
                 column="productId"
                 type="string">
                 <generator class="native"/>
             </id>
             <property name="categoryId" column="category" type="string"/>
             <property name="name" column="name" type="string"/>
             <property name="description" column="description" type="string"/>

          </class>

      </hibernate-mapping>

    In the mapping file, we first identify the package and particular class (org. springframework.samples.jpetstore.domain.Product) that we are mapping. We have to tell it what table to map to ("product", in this case) and then map the individual properties of the domain object to the columns in the table. This file needs to be saved somewhere on the class path; we’ll create a new folder in the project structure called “hibernate” to hold our map files and our new DAOs.

    Hibernate DAOs

    The next step is to create a DAO that uses Hibernate as the persistence layer instead of the SQL mappings used in the original version. The new DAO needs to implement the ProductDao interface, just like the original DAO. However, the implementation of that interface will be totally different.

    Here is the code for the new DAO:

      public class HibernateProductDao implements ProductDao{
          SessionFactory factory;
          Configuration cfg;
          public HibernateProductDao() {
              try {
                  cfg = new Configuration().addClass(
                   org.springframework.samples. jpetstore.domain.Product.class);
                  factory = cfg.buildSessionFactory();
              } catch (Exception ex) {
                  System.out.println("Hibernate configuration failed: " + ex);
              }
          }

          public List getProductListByCategory(String categoryId)
            
    throws DataAccessException {
              List results = null;
              try {
                  Session session = factory.openSession();
                  results = session.find("from product where product.category = ?",
                 categoryId, Hibernate.STRING);
                 session.close();
              } catch (Exception ex) {
                 System.out.println("Failed to connect to database:" + ex);
              }
               return results;
          }

          public List searchProductList(String keywords) throws DataAccessException {
              return null;
          }

          public Product getProduct(String productId) throws DataAccessException {
              Product p = null;
              try {
                 
    Session session = factory.openSession();
                  p = (Product)session.load(Product.class, productId);
                  session.close();
             
    } catch (Exception ex) {
                  System.out.println("failed to connect to database: " + ex);
                  p = null;
             
    }

              return p;
          } 

      }

    First, we need a way to interact with Hibernate. As shown in Chapter 7, we need to create a HibernateSessionFactoryand use it to get aSessionwith which to interact with the database. The DAO’s constructor instantiates a new Hibernate
    configuration, loading the mapping file from the class path based on the name of the class added to the configuration. Then, it gets theSessionFactoryfrom the Configuration.

    Each method uses the SessionFactory to open a newSessionwith the database. ThegetProductmethod is the most straightforward; first, we get the Session. Then, we ask the session to load an instance of theProductclass, given its productId. Note that the result from thesession.load()call is of typeObject, which we have to cast to Product. Finally, we close the Session. Hibernate handles all the SQL commands, looking up the mapping files, matching the productId to the right column in the table, populating all the fields, everything.

    ThegetProductListByCategory()method is less straightforward; it takes acategoryIdand returns a List of all the products that match that category. In this case, we can’t rely on the built-in SQL generation; we have to create our own query. Again, we first grab aSessionfrom theSessionFactory, then use thesession.find()method, which returns aList ofObjects. Find takes three parameters in this case: the HSQL query (which contains a placeholder for a query parameter, marked with a “?”), the value to fill into the query parameter, and the type of that parameter.

    As shown in Chapter 7, HSQL (Hibernate SQL) queries look a lot like regular SQL statements, except here we left off the “SELECT [values]” part of the statement, since Hibernate will fill those in for us based on the mapping. This method will now look up all the rows in the Product table wherecategoryIdequals the value passed in to the method, and create one instance ofProductfor each row in the resultset. All the product instances are placed in aListand returned.

    The final method of the DAO,searchProductList, would be a lot more complex, but luckily, we don’t have to implement it. Since we have already replaced the original search functionality with the Simple Spider, this method will never be called now, so we simply returnnull(we have to do something, since theProductDaointerface still mandates its inclusion).

    To finish out the new architecture, we just repeat these steps for each of the remaining five domain objects. Each gets a mapping file and an implementation of the appropriate DAO interface.

    More Java Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Better, Faster, Lighter Java," published...
     

    Buy this book now. This article is excerpted from the book Better, Faster, Lighter Java, written by Bruce A. Tate and Justin Gehtland (O'Reilly; ISBN: 0596006764). Check it out today at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek