Java Reference
In-Depth Information
4.4.2
Using the Spring ORM classes
In chapter 1, I explained that one of the key benefits of using Spring is that it
makes implementing Hibernate and JDO applications considerably easier. One
reason why it simplifies application development is because, as you will see in
chapters 7 and 8, it provides AOP interceptors and filters for opening and closing
JDO and Hibernate connections and managing transactions. Another reason why
Spring makes development easier is it provides the JdoTemplate and Hibernate-
Template classes, which are easy-to-use wrappers around the JDO and Hibernate
APIs. These ORM template classes implement the boilerplate code that's required
when using a persistence framework and significantly simplify the implementa-
tion of repositories. In order to see the benefit of using Spring's ORM template
classes, let's first look an example of a repository that does not use them.
Using Hibernate without a Spring HibernateTemplate
Listing 4.1 shows an example Hibernate repository method, which loads an object
by calling Session.load() . It uses SessionFactoryUtils , which is a Spring frame-
work helper class that defines various static methods for managing Hibernate Ses-
sion s and mapping exceptions. The repository method calls SessionFactory-
Utils.getSession() to get a Session and SessionFactoryUtils.releaseSession()
to release the Session . The method uses a try/catch/finally to map the Hiber-
nateException to a Spring data access exception and to ensure that release-
Session() is always called.
Listing 4.1
HibernatePendingOrderRepositoryImpl
public class HibernatePendingOrderRepositoryImpl
implements PendingOrderRepository {
private SessionFactory sessionFactory;
public HibernatePendingOrderRepositoryImpl(
SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public PendingOrder findOrCreatePendingOrder(String pendingOrderId) {
if (pendingOrderId != null)
return findPendingOrder(pendingOrderId);
else
return createPendingOrder();
}
public PendingOrder findPendingOrder(String pendingOrderId) {
Session session =
 
 
 
 
 
 
Search WWH ::




Custom Search