Java Reference
In-Depth Information
6.4 Implementing a repository using Hibernate
In the previous section we looked at how to persist a domain model class using
Hibernate. The other part of implementing a persistent domain model is to imple-
ment the repositories, which define methods for creating, finding, and deleting
persistent objects. In this section, we'll show you how to use a test-driven approach
to implement a repository that uses the Hibernate API s to manipulate persistent
objects. We'll use the RestaurantRepository.findAvailableRestaurants()
method, which finds the restaurants that serve a given delivery address and time, as
an example. We'll first write some mock object tests for the RestaurantRepository ,
and then we'll write the method. After that, we'll write some database tests for the
Hibernate query that is executed by the repositories to find the restaurants.
6.4.1
Writing a mock object test for a repository method
Mock object tests are a very effective way to directly test the functionality imple-
mented by the repository independently of the persistence framework and the
database. The findAvailableRestaurants() method retrieves the available restau-
rants by executing a query; therefore, a mock object test for this method must
invoke it with a delivery time and address and verify that it calls the Hibernate
API s to execute the expected query with the expected parameters. As you will see,
the test is easy to write and executes extremely quickly.
To write the mock object test, we must decide how the repository executes the
query. One easy decision to make is to use named queries. Rather than embed the
Hibernate query string in the code, it makes more sense to use a named query
and store the query string in the O/R mapping document. This makes the query
easier to read and change and also simplifies the code.
Another decision is which API to use. The repository could use the Hibernate
Session and Query API s directly. However, a better approach—one that requires
fewer lines of code and that is easier to mock—is Spring's HibernateTemplate
class. It provides a number of convenience methods that wrap the Hibernate API .
In particular, it provides a HibernateTemplate.findByNamedQueryAndNamedParam()
method that takes three parameters: the query name, parameter names, and
parameter values.
Using HibernateTemplate.findByNamedQueryAndNamedParam() makes testing
findAvailableRestaurants() very straightforward. A test can use a mock Hiber-
nateTemplate that verifies that findByNamedQueryAndNamedParam() is called with
the correct arguments. It can pass the mock HibernateTemplate to the repository
using constructor injection. Listing 6.4 shows the test for this method.
 
 
 
 
 
Search WWH ::




Custom Search