Wednesday, March 2, 2011

Generating a FlatXmlDataSet for dbunit

If you use Unitils, you can simplify the sample code provided by DBUnit

(see "How to extract a flat XML dataset from my database? ")

Unitils unitilsInstance = Unitils.getInstance();

Properties properties = unitilsInstance.getConfiguration();

// database connection
Class driverClass = Class.forName(properties.getProperty("database.driverClassName")); 
Connection jdbcConnection = DriverManager.getConnection(properties.getProperty("database.url"), properties.getProperty("database.userName"), properties.getProperty("database.password"));
IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

// partial database export
QueryDataSet partialDataSet = new QueryDataSet(connection);
partialDataSet.addTable("PRODUCT", "SELECT * FROM MYTABLE");

FlatXmlDataSet.write(partialDataSet, new FileOutputStream("c:/MYTABLE.xml"));

It works like a charm... never ever again shall I manually produce those boring dataset XML files...

No comments: