我正在尝试在 Java中创建一个数据库侦听器( postgres )。每次用户插入或删除表的条目时,我都想分别接收插入或删除的值。
为此,我创建了一个触发器,如下所示,它在插入后运行并返回感兴趣的相应行字段。(我还创建了一个类似的删除字段)。
CREATE OR REPLACE FUNCTION notify() RETURNS trigger AS $insert$
DECLARE
command_string text;
BEGIN
command_string := format('{"data":"%s"}',NEW.data);
PERFORM pg_notify('demo', command_string);
RETURN NEW;
END;
$insert$ LANGUAGE plpgsql;
问题是通过使用函数pg_notify(..)我只能在我的 Java 应用程序中检索值作为字符串。理想情况下,我希望有一个触发器,能够返回序列化的数据,维护其各自的类型(字节 []、整数等)
为此,我正在考虑使用 Pljava:https ://github.com/tada/pljava/wiki 。虽然能够创建所需的触发器,但我不知道每次删除或插入一行时我是否会从我的 java 应用程序中提取值。
关于如何构建此功能的任何想法?
为了完整起见,下面是我用来从 pg_notify 中检索值的代码。
@Override
public void run() {
while (running) {
try {
try ( // Dummy Pull
Statement stmt = dbConnection.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT 1");
rs.close();
}
// Retreive Notifications
PGNotification notifications[] = pgconn.getNotifications();
if (notifications != null) {
for (PGNotification notification : notifications) {
logger.debug("Got notification: " + notification.getName());
logger.debug("Got payload: " + notification.getParameter());
}
}
Thread.sleep(pollingInterval);
} catch (InterruptedException | SQLException ex) {
logger.fatal("WATCHER ABORTED",ex);
}
}
}