01: package org.directwebremoting.hibernate;
02:
03: import java.sql.Connection;
04: import java.sql.DriverManager;
05: import java.sql.SQLException;
06: import java.sql.Statement;
07:
08: import org.apache.commons.logging.LogFactory;
09: import org.apache.commons.logging.Log;
10:
11: /**
12: * Database abstraction code to help Hibernate tests
13: * @author Joe Walker [joe at getahead dot ltd dot uk]
14: */
15: public class Database {
16: /**
17: * The commands we execute to create and populate a database
18: */
19: private static final String[] STARTUP = {
20: "CREATE TABLE parent (id INT PRIMARY KEY, name VARCHAR);",
21: "CREATE TABLE child (id INT PRIMARY KEY, name VARCHAR, owner INT);",
22: "ALTER TABLE child ADD CONSTRAINT child_owner_fk FOREIGN KEY (owner) REFERENCES parent (id);",
23: "INSERT INTO parent (id, name) VALUES (1, 'fred');",
24: "INSERT INTO child (id, name, owner) VALUES (2, 'jim', 1);", };
25:
26: /**
27: * Create a new in-memory database using HSQLDB
28: */
29: public static synchronized void init() {
30: if (inited) {
31: return;
32: }
33:
34: Connection con = null;
35: Statement stmt = null;
36:
37: try {
38: Class.forName("org.hsqldb.jdbcDriver");
39: con = DriverManager.getConnection(
40: "jdbc:hsqldb:mem:dwr-test", "sa", "");
41: stmt = con.createStatement();
42: for (String sql : STARTUP) {
43: stmt.execute(sql);
44: }
45: } catch (Exception ex) {
46: log.warn("Failed to start hsqldb", ex);
47: } finally {
48: try {
49: if (con != null)
50: con.close();
51: if (stmt != null)
52: stmt.close();
53: } catch (SQLException ex) {
54: log.warn("Exception on close", ex);
55: }
56:
57: inited = true;
58: }
59: }
60:
61: /**
62: * Has init() been called?
63: */
64: private static boolean inited = false;
65:
66: /**
67: * The log stream
68: */
69: private static final Log log = LogFactory.getLog(Database.class);
70: }
|