Java Reference
In-Depth Information
argument.
HibernateTemplate
is typically instantiated by Spring's bean factory and
passed by dependency injection to the repositories that need it.
Using an
ORM
template class also facilitates testing. The repository methods
that call a convenience method can be tested with a mock template object. A test
case can construct a repository passing in a mock template object and verify that
the expected method is called.
Despite these advantages, you cannot always use the convenience methods
because they do not expose all of the functionality of the persistence framework's
API
s.
4.4.3
Making repositories easier to test
A repository must call the persistence framework
API
s directly if the
ORM
template
does not expose the functionality that it needs. It could use the
SessionFactory-
Utils
and
PersistenceManagerFactoryUtils
classes to obtain a connection, but
code that uses those classes is more difficult to test because it can't be tested with
mock objects. A better approach is to use an
ORM
template class to execute what
Spring refers to as a callback.
The trouble with anonymous callback classes
A Spring callback object is an instance of a class that implements a callback inter-
face. It has a method that is passed a persistence framework connection as a
parameter, and it can manipulate persistent objects. The simplest way to execute a
callback with an
ORM
template class is to use an anonymous class. For example,
the
RestaurantRepository
's
findRestaurants()
method could use the
JdoTem-
plate
to execute a callback that uses the
Query
interface directly:
public class JDORestaurantRepositoryImpl extends JdoDaoSupport
implements RestaurantRepository {
public List findRestaurants(final Address deliveryAddress,
final Date deliveryTime) {
JdoTemplate jdoTemplate = getJdoTemplate();
return (List) jdoTemplate.executeFind(new JdoCallback() {
public Object doInJdo(PersistenceManager pm) {
Map parameters = makeParameters(deliveryAddress,
deliveryTime);
Query query = pm.newQuery(Restaurant.class);
query.declareVariables("TimeRange tr");
…
return query.executeWithMap(parameters);
}
});
}
Search WWH ::
Custom Search