Java Reference
In-Depth Information
The infrastructure class hierarchy depicted in figure 18.1 is quite similar to the one
used in chapter 17. The only difference is the root class,
AbstractJpaTestCase
, which
is shown in listing 18.6.
Listing 18.6
Root class of testing infrastructure,
AbstractJpaTestCase
[...]
public abstract class
AbstractJpaTestCase {
private static
EntityManagerFactory entityManagerFactory;
protected static
Connection connection;
protected
EntityManager em;
@BeforeClass
public static
void setupDatabase()
throws
Exception {
entityManagerFactory =
Persistence.createEntityManagerFactory("chapter-18");
connection = getConnection(entityManagerFactory);
}
B
C
@AfterClass
public static void
closeDatabase()
throw
s Exception {
if
( connection !=
null
) {
connection.close();
connection =
null
;
}
if
( entityManagerFactory !=
null
) {
entityManagerFactory.close();
}
}
D
E
@Before
public void
setEntityManager() {
em = entityManagerFactory.createEntityManager();
}
@After
public void
closeEntityManager() {
em.close();
}
F
public static
Connection getConnection(Object object)
throws
Exception {
Connection connection =
null
;
if
( object
instanceof
EntityManagerFactoryImpl ) {
EntityManagerFactoryImpl impl = (EntityManagerFactoryImpl) object;
SessionFactory sessionFactory = impl.getSessionFactory();
if
( sessionFactory
instanceof
SessionFactoryImpl ) {
SessionFactoryImpl sfi = (SessionFactoryImpl) sessionFactory;
Settings settings = sfi.getSettings();
ConnectionProvider provider = settings.getConnectionProvider();
connection = provider.getConnection();
}
}
return
connection;
}
G