问题
I tried run a simple class to call TRIGGER from Java code, I used H2 DB, can you help me? Here is my simple code (like sample code in 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();
}
}
And errors : Exception in thread "main" org.h2.jdbc.JdbcSQLException: Error creating or initializing trigger "INV_INS" object, class "vn.com.khangpn.core.trigger.TriggerTest$MyTrigger", cause: "org.h2.message.DbException: Class ""vn.com.khangpn.core.trigger.TriggerTest$MyTrigger"" not found [90086-169]"; see root cause for details; SQL statement:
回答1:
In H2, the trigger class must be available in the classpath of the database engine (when using the server mode, it must be in the classpath of the server).
来源:https://stackoverflow.com/questions/14124099/cannot-call-trigger-in-h2-db