Java
  Home arrow Java arrow Page 4 - 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 - Spring’s Built-In Hibernate Support


    (Page 4 of 4 )

    Now that you have seen the explicit way to do things, let’s briefly take a look at the supporting infrastructure Spring provides for Hibernate. Spring, through its “inversion of control” architecture, can fully manage the creation of the SessionFactory for you. In addition, it provides a new class, HibernateDaoSupport, which allows your application-specific DAOs to reuse standard, template-derived calls for interacting with the datasource.

    To set it up, you need to change your DAOs to extend HibernateDaoSupport. So, this:

      public class HibernateProductDao implements ProductDao

    becomes:

      public class HibernateProductDao extends HibernateDaoSupport implements ProductDao

    Then add the following code to enable Spring to pass in aSessionFactory:

      private SessionFactory sessionFactory; 
      public void setSessionFactory(SessionFactory sessionFactory) {
          this.sessionFactory = sessionFactory;
      }

    After adding this, your DAOs can use an object provided byHibernateDaoSupport calledHibernateTemplate. This new class, accessed through the newgetHibernateTemplate()method inherited fromHibernateDaoSupport, exposes a series of helper methods for interacting with the database, such asload,save,update,saveOrUpdate,get, andfind. OurProductDao becomes a lot simpler:

      public class HibernateProductDao extends HibernateDaoSupport implements ProductDao {
          private SessionFactory sessionFactory;

          public void setSessionFactory(SessionFactory sessionFactory){
              this.sessionFactory = sessionFactory;
          }

          public HibernateProductDao() {
          }

          public List getProductListByCategory(String categoryId) {
              return getHibernateTemplate().find("from product where product.category = ?",
             categoryId, Hibernate.STRING);
          }

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

          public Product getProduct(String ProductID) throws DataAccessException {
              return (Product) getHibernateTemplate().load(Product.class, productId);
          }

     
    }

    To configure all of this, you’ll have to make some changes to your configuration files. You now have to add a property for theSessionFactorywhere you defined theProductDao bean:

      <bean id="productDao"
      
    class="org.springframework.samples. jpetstore.dao.hibernate.HibernateProductDao">
          <property name="sessionFactory"/>
          <ref bean="mySessionFactory"/>
      </bean>

    Then add a definition of themySessionFactorybean:

      <bean id="mySessionFactory"
       
    class="org.springframework.orm. hibernate.LocalSessionFactoryBean">
      <property name="mappingResources">
      <list>
         
    <value>product.hbm.xml</value>
      </list>
      <!-- etc. -->
      </property>
      <property name="hibernateProperties">
      <props>
      <prop key="hibernate.dialect">net.sf.hibernate. dialect.HSQLDialect</prop>
      </props>
      </property>
      <property name="dataSource">
          <ref bean="dataSource"/>
      </property>
      </bean>

    Add as many entries to themappingResources property as you have map files, and make sure that thedataSourceproperty refers to your already-configureddataSourcebean. With these minimal changes, your DAOs become much more standardized and compacted, and Spring handles all yourSessionFactoryandSessionimplementation details for you. You are free to focus, yet again, on the problem at hand rather than the supporting framework.

    That’s it! Once again, we’ve managed to replace an entire swath of existing code without touching the original codebase itself. We have simply added new classes to the project and changed some configuration settings, and voila! Hibernate.

    Principles in Action

    • Keep it simple: domain objects remain unaware of persistence logic, Hibernate manages all configuration
    • Choose the right tools: Hibernate
    • Do one thing, and do it well: the domain model is focused on the business problem, the DAOs focus on data manipulation and are database-agnostic
    • Strive for transparency: domain model is completely unaware of persistence layer
    • Allow for extension: Spring configuration and IoC allow us to change persistence layers

    Summary

    Over the last two chapters, we have taken an initial customer’s requirements for a generic, flexible web site search engine and refined them to meet our core principles. We then designed a simple, straightforward application that met those requirements—and then some—and made use of existing tools (however unorthodoxly) to accomplish a complex set of tasks. The result was a solution to the initial requirements that came in well below the $18,000 that Google charges for its search appliance, even if we had billed the customer not only for design and development, but also for all the time spent researching the included open source tools and writing these two chapters! And, frankly, we aren’t cheap. Simplicity really does have its rewards.

    We learned how easy it is to integrate two applications designed with our core principles in mind. Since thejPetStoresample is built on a lightweight framework (Spring) and makes good use of the world’s most common design pattern (MVC), it was child’s play to introduce a replacement service for the limited one provided.

    Since the Spider is well factored and provides flexibility through its configuration service, it is easy to adapt it for use in a new context, in a container-based environment, and with an entirely new user interface, using only three changed lines of code to the original application (and those lines only added a new scoping keyword). And since Hibernate is also built on these same principles, it was incredibly easy to swap it into the project in place of the existing persistence mechanism.

    These examples demonstrate that Java doesn’t have to be hard. In fact, if you focus on the principles outlined in this book, Java can be downright fun.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · 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 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek