Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

java - H2 - How to create a database trigger that log a row change to another table?

How to create a database trigger that log a row change to another table in H2?

In MySQL, this can be done easily:

CREATE TRIGGER `trigger` BEFORE UPDATE ON `table`
  FOR EACH ROW BEGIN
    INSERT INTO `log`
    (
      `field1`
      `field2`,
      ...
    )
    VALUES
    (
      NEW.`field1`,
      NEW.`field2`,
      ...
    ) ;
    END;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Declare this trigger:

CREATE TRIGGER my_trigger
BEFORE UPDATE
ON my_table
FOR EACH ROW
CALL "com.example.MyTrigger"

Implementing the trigger with 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 {}
}

Implementing the trigger with jOOQ:

Since you added the jOOQ tag to the question, I suspect this alternative might be relevant, too. You can of course use jOOQ inside of an H2 trigger:

    @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();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...