Java Reference
In-Depth Information
ignore the result. This quick and easy approach can catch lots of basic errors and
is often all you need to do for simple queries.
For more complex queries, it is usually important to detect bugs in the logic of
the query such as using < instead of <= . To catch these kinds of bugs, we need to
write tests that populate the database with test data, execute the query, and verify
that it returns the expected objects. Unfortunately, these kinds of tests are time
consuming to both write and execute.
There are a couple of ways a test can execute a query. One option is to execute
the query directly using the Spring and Hibernate API s. The other option is to
execute the query indirectly by invoking the repository. Which of these options is
better depends on various factors, including the complexity of the repository. If
the repository is fairly simple, then it can be easier to test the query by calling the
repository because it is straightforward to execute the query with a particular set
of arguments. If the repository is more complex, then testing the queries directly
can be easier.
To be able to test a query independently of the repository that executes it, the
query must be stored separately from the repository. The easiest way to accomplish
this is to use named queries that are defined in the mapping document. Both Hiber-
nate and JDO 2.0 let you define queries in the XML mapping document and provide
an API for executing them by name. In addition to keeping the queries separate
from the repositories, it is a lot more manageable to define multiline queries in an
XML document than it is to do so in Java code by concatenating multiple strings.
Alternatively, if you are using an ORM framework that doesn't support named que-
ries, such as a JDO 1 .x implementation, then you should store the queries in a prop-
erties file. Once you have done this, the queries can be tested separately.
Verifying that the schema matches the mapping
Unless the schema is generated from the O/R mapping, it is possible for the map-
ping and the schema to get out of sync. It is quite easy, for example, to forget to add
a new column to a table after defining the mapping for a field. Consequently, we
must write tests that verify that the database schema matches the O/R mapping.
One way to test the database schema is to extract the table and column names
from the mapping document and use the JDBC metadata API s to verify that every
table and column exists in the database schema. This kind of test executes fairly
quickly because it makes relatively few calls to the database. However, the one
drawback is that you have to write a lot of code to implement this kind of test.
A much easier option that you can use some with ORM frameworks such as Hiber-
nate is the ORM framework's schema generation feature. Some ORM frameworks
 
Search WWH ::




Custom Search