Have a look at DBUnit - their how-to is at http://dbunit.sourceforge.net/howto.html
It does exactly what you're looking for.
The DBunit site has lots of examples. What I do is the following:
set up the d/b in the @Before method, so each test gets a clean fixture. An example of the @Before method is:
Connection conn = dataSource.getConnection();
try {
IDatabaseConnection connection = new DatabaseConnection(conn);
DatabaseConfig config = connection.getConfig();
config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new HsqldbDataTypeFactory());
DatabaseOperation.CLEAN_INSERT.execute(connection, loadDutyData());
DatabaseOperation.CLEAN_INSERT
.execute(connection, loadHelperData());
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
where the loadHelperData() method does the folllowing:
DataFileLoader loader = new FlatXmlDataFileLoader();
IDataSet ds = loader.load(TEST_DATA_FILE_HELPER);
return ds;
The load method simply takes an xml file representing the database. See the DBUnit documentation for much more information.