Java Reference
In-Depth Information
Table C-1.
The Core
HibernateTemplate
Methods
Method
Description
bulkUpdate()
Performs a bulk update or delete on the database, according to the provided
HQL query and entities
contains()
Determines whether the given object exists as an entity in the database
delete()
Deletes an entity from the database
find()
Carries out an HQL query
get()
Obtains an entity by its
id
(primary key)
persist()
Saves an entity to the database
refresh()
Refreshes an entity from the database
save()
Saves an entity to the database
saveOrUpdate()
Saves an entity to the database or updates it as appropriate
update()
Updates an entity in the database
When a more complex set of operations is required than can be achieved in a single line,
the
execute()
method is used to invoke an instance of
HibernateCallback
. Our example appli-
cation uses
HibernateCallback
to implement its
createArticle()
method. This is shown in
Listing C-10.
Listing C-10.
Invoking a
HibernateCallback
Object from the Template's
execute()
Method
public Paper createArticle(final Integer paperId,final Article article) {
HibernateCallback callback = new HibernateCallback() {
public Object doInHibernate(Session session) {
Paper paper = (Paper)session.get(Paper.class,paperId);
paper.addArticle(article);
session.update(paper);
return paper;
}
};
return (Paper)getHibernateTemplate().execute(callback);
}
Although this allows us to invoke more complex code from the
HibernateTemplate
class,
and
HibernateTemplate
obviates the need for specific management of the session, it doesn't
make the implementation particularly terse, and probably makes it slightly harder to under-
stand. Listing C-11 shows how the same method can be implemented without using
HibernateTemplate
.
Search WWH ::
Custom Search