Java Reference
In-Depth Information
H
protected void
beginTransaction() {
em.getTransaction().begin();
}
I
protected void
commitTransaction() {
em.getTransaction().commit();
}
J
protected void
commitTransaction(
boolean
clearContext) {
commitTransaction();
if
( clearContext ) {
em.clear();
}
}
}
The first step is to create an
EntityManagerFactory
, and as this is an expensive opera-
tion, it's done only once, using the
@Before
annotation. Notice that this initialization
doesn't contain any information about the
JPA
provider (Hibernate) or database
(
HSQLDB
) used in the test case. That information is defined in the persistence.xml
and hibernate.properties files (shown in listings 18.7 and 18.8, respectively).
Although when you use
JPA
you don't need to deal with low-level
JDBC
interfaces
directly, DbUnit needs a database connection. You could define the
JDBC
settings
for this connection in a properties file, but that would be redundant; it's better
to extract the
JDBC
connection from
JPA
's entity manager. Also notice that such
reuse is the reason why this chapter's
AbstractJpaDbUnitTestCase
(which isn't
shown here either, but is the same as chapter's 17
AbstractDbUnitTestCase
) extends
AbstractJpaTestCase
, and not vice versa. If
@BeforeClass
methods didn't have to
be static, such reversal of fortune wouldn't be necessary:
AbstractJpaDbUnitTest-
Case
could define a protected
getConnection()
method, which in turn would be
overridden by
AbstractJpaTestCase
.
Don't forget to close at
@After
what you opened at
@Before
!
The
EntityManager
, which is the object effectively used by the test cases, is created
before each test method and closed thereafter. This is the way
JPA
is supposed to be
used, and this object creation is cheap.
Unfortunately, there's no standard way to extract the
JDBC
Connection
from the
JPA
EntityManagerFactory
, so it's necessary to use proprietary
API
s from the chosen
JPA
vendors.
Because our test cases will manually manage transactions, it's convenient to create
helper methods for this task.
Similarly, some test cases will test how objects behave outside the
JPA
context, so we
define an overloaded
commitTransaction()
, which also clears the context.
B
C
D
F
E
,
G
H
,
I
J
The
JPA
configuration is quite simple: persistence.xml (listing 18.7) only defines a per-
sistence-unit name, and the vendor-specific configuration is defined in hibernate.prop-
erties (listing 18.8). Such a split is a good practice, because if the test cases must change