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