package ajb;
import org.hsqldb.jdbc.jdbcDataSource;
import org.apache.ddlutils.model.*;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformFactory;
import org.apache.commons.beanutils.DynaBean;
import java.util.ArrayList;
import java.util.Iterator;
import java.sql.Connection;
public class Main {
public static void main(String[] args) throws Exception {
System.err.println("Start my Test");
jdbcDataSource dataSource = new jdbcDataSource();
dataSource.setUser("sa");
dataSource.setDatabase("jdbc:hsqldb:file:testdb/ddlutils_hsqldb");
//DatabaseIO dbio = new DatabaseIO();
//Database database = dbio.read("schema.xml");
Database database = newDb();
Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
platform.createModel(database, true, true); // drop tables, continueOnError
//Connection con = dataSource.getConnection();
// "author" is a table of the model
DynaBean author = database.createDynaBeanFor("author", false);
// "name" and "whatever" are columns of table "author"
author.set("author_id", 123);
author.set("name", "James");
author.set("organisation", "MyOrg");
platform.insert(//con, without con then new con from pool, no commit!
database, author);
//con.commit(); // meaningless, autocommit assumed by ddlutils.
author.set("organisation", "MyNewOrg");
platform.update(//con,
database, author);
author.set("parent_id", 123);
platform.update(//con,
database, author);
// author.set("parent_id", 321); // throws exception, good.
// platform.update(//con,
// database, author);
ArrayList params = new ArrayList();
params.add("James");
Iterator it = platform.query(database, // no con parameter!
"select * from author where name = ?",
params);
System.err.println("Outputing...");
while ( it.hasNext() ) {
DynaBean book = (DynaBean) it.next();
System.err.println(book.get("name") + " = " + book.get("organisation"));
}
}
static Database newDb() throws Exception { // extracted out of DatabaseIO
Database database = new Database();
database.setName("testdb");
Table author= new Table();
author.setName("author");
Column id = addNewColumn(author, "author_id", "INTEGER");
id.setPrimaryKey(true);
id.setRequired(true);
addNewColumn(author, "name", "VARCHAR");
addNewColumn(author, "organisation", "VARCHAR");
Column parent = addNewColumn(author, "parent_id", "INTEGER");
ForeignKey fkey = new ForeignKey("author_parent");
fkey.setForeignTable(author);
author.addForeignKey(fkey);
Reference ref = new Reference(parent, id);
fkey.addReference(ref);
database.addTable(author);
return database;
}
static Column addNewColumn(Table table, String name, String type) {
Column column = new Column();
column.setName(name);
column.setType(type);
table.addColumn(column);
return column;
}
}
|