Java Reference
In-Depth Information
Listing C-11.
The
createArticle()
Method Without
HibernateTemplate
public Paper createArticle(final Integer paperId,final Article article) {
Session session = getSession();
Paper paper = (Paper)session.get(Paper.class,paperId);
paper.addArticle(article);
session.update(paper);
releaseSession(session);
return paper;
}
Regardless of how you use it, configuring your
HibernateDaoSupport
-derived template is
extremely simple. The basic requirement is that you provide its
sessionFactory
property with
a session factory bean from which to obtain Hibernate
Session
objects (see Listing C-12).
Listing C-12.
Configuring a
HibernateDaoSupport
-Derived Bean
<bean id="sampleDao"
class="com.hibernatebook.spring.dao.PaperDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
In practice, however, this is usually made somewhat more complex by the need to declare
the transactional behavior that applies to the DAO's methods.
Declarative Transaction Management
The
getAll()
method as implemented in Listings C-8 and C-9 omits any explicit transaction
management. It is entirely possible to manage transactions directly—you have access to the
Hibernate
Session
object, and this can be used as shown in Listing C-13.
Listing C-13.
Explicit Transaction Management (Not Recommended)
@SuppressWarnings("unchecked")
public List<Paper> getAll() {
Session session = getSession();
session.beginTransaction();
List<Paper> papers = (List<Paper>)session.createQuery("from Paper").list();
session.getTransaction().commit();
releaseSession(session);
return papers;
}
However, while this is possible, it is not recommended—the use of
OpenInViewInterceptor
or
OpenInViewFilter
can prevent this code from behaving as you might expect, as can various
other indirectly applied beans. This is equally applicable when you are using
HibernateTemplate
.
Because of these risks, you should favor the use of declarative transaction management.
With this, the beans' methods are marked as being the boundaries of transactions, and the
appropriate transaction isolation level and propagation behavior can be specified.
Search WWH ::
Custom Search