无法在H2 DB中调用触发器

时间:2013-01-02 14:51:49

标签: java netbeans h2

我尝试运行一个简单的类从Java代码调用TRIGGER,我使用H2 DB,你能帮助我吗?这是我的简单代码(如H2中的示例代码):

public class TriggerTest {

public static void main(String[] args) throws Exception {
    System.out.println(TriggerTest.MyTrigger.class.getName());
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/chap1", "sa", "sa");
    Statement stat = conn.createStatement();
    stat.execute("Drop Table if exists INVOICE");
    stat.execute("Drop Table if exists INVOICE_SUM");
    stat.execute("CREATE TABLE INVOICE(ID INT PRIMARY KEY, AMOUNT DECIMAL)");
    stat.execute("CREATE TABLE INVOICE_SUM(AMOUNT DECIMAL)");
    stat.execute("INSERT INTO INVOICE_SUM VALUES(0.0)");
    stat.execute("CREATE TRIGGER INV_INS AFTER INSERT ON INVOICE FOR EACH ROW CALL \""+TriggerTest.MyTrigger.class.getName()+"\"");
    stat.execute("CREATE TRIGGER INV_UPD AFTER UPDATE ON INVOICE FOR EACH ROW CALL \""+TriggerTest.MyTrigger.class.getName()+"\"");
    stat.execute("CREATE TRIGGER INV_DEL AFTER DELETE ON INVOICE FOR EACH ROW CALL  \""+TriggerTest.MyTrigger.class.getName()+"\"");

    stat.execute("INSERT INTO INVOICE VALUES(1, 10.0)");
    stat.execute("INSERT INTO INVOICE VALUES(2, 19.95)");
    stat.execute("UPDATE INVOICE SET AMOUNT=20.0 WHERE ID=2");
    stat.execute("DELETE FROM INVOICE WHERE ID=1");

    ResultSet rs;
    rs = stat.executeQuery("SELECT AMOUNT FROM INVOICE_SUM");
    rs.next();
    System.out.println("The sum is " + rs.getBigDecimal(1));
    conn.close();
}

public static class MyTrigger implements Trigger {

    public void init(Connection conn, String schemaName, String triggerName, String tableName, boolean before, int type) {
        // Initializing trigger
    }

    public void fire(Connection conn,
            Object[] oldRow, Object[] newRow)
            throws SQLException {
        BigDecimal diff = null;
        if (newRow != null) {
            diff = (BigDecimal) newRow[1];
        }
        if (oldRow != null) {
            BigDecimal m = (BigDecimal) oldRow[1];
            diff = diff == null ? m.negate() : diff.subtract(m);
        }
        PreparedStatement prep = conn.prepareStatement(
                "UPDATE INVOICE_SUM SET AMOUNT=AMOUNT+?");
        prep.setBigDecimal(1, diff);
        prep.execute();
    }

}

错误: 线程“main”中的异常org.h2.jdbc.JdbcSQLException:创建或初始化触发器“INV_INS”对象时出错,类“vn.com.khangpn.core.trigger.TriggerTest $ MyTrigger”,原因:“org.h2.message。 DbException:Class“”vn.com.khangpn.core.trigger.TriggerTest $ MyTrigger“”not found [90086-169]“;了解细节的根本原因; SQL语句: