声明此触发器:
CREATE TRIGGER my_trigger
BEFORE UPDATE
ON my_table
FOR EACH ROW
CALL "com.example.MyTrigger"
使用 Java/JDBC 实现触发器:
public class MyTrigger implements Trigger {
@Override
public void init(Connection conn, String schemaName,
String triggerName, String tableName, boolean before, int type)
throws SQLException {}
@Override
public void fire(Connection conn, Object[] oldRow, Object[] newRow)
throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO log (field1, field2, ...) " +
"VALUES (?, ?, ...)")
) {
stmt.setObject(1, newRow[0]);
stmt.setObject(2, newRow[1]);
...
stmt.executeUpdate();
}
}
@Override
public void close() throws SQLException {}
@Override
public void remove() throws SQLException {}
}
使用 jOOQ 实现触发器:
由于您在问题中添加了jOOQ标签,因此我怀疑此替代方案也可能相关。当然,您可以在 H2 触发器中使用 jOOQ:
@Override
public void fire(Connection conn, Object[] oldRow, Object[] newRow)
throws SQLException {
DSL.using(conn)
.insertInto(LOG, LOG.FIELD1, LOG.FIELD2, ...)
.values(LOG.FIELD1.getDataType().convert(newRow[0]),
LOG.FIELD2.getDataType().convert(newRow[1]), ...)
.execute();
}