Getting events from a database

mainstringargs picture mainstringargs · May 1, 2009 · Viewed 27.3k times · Source

I am not very familiar with databases and what they offer outside of the CRUD operations.

My research has led me to triggers. Basically it looks like triggers offer this type of functionality:

(from Wikipedia)

There are typically three triggering events that cause triggers to "fire":

  • INSERT event (as a new record is being inserted into the database).
  • UPDATE event (as a record is being changed).
  • DELETE event (as a record is being deleted).

My question is: is there some way I can be notified in Java (preferably including the data that changed) by the database when a record is Updated/Deleted/Inserted using some sort of trigger semantics?

What might be some alternate solutions to this problem? How can I listen to database events?

The main reason I want to do this is a scenario like this:

I have 5 client applications all in different processes/existing across different PCs. They all share a common database (Postgres in this case).

Lets say one client changes a record in the DB that all 5 of the clients are "interested" in. I am trying to think of ways for the clients to be "notified" of the change (preferably with the affected data attached) instead of them querying for the data at some interval.

Answer

Javamann picture Javamann · May 1, 2009

Using Oracle you can setup a Trigger on a table and then have the trigger send a JMS message. Oracle has two different JMS implementations. You can then have a process that will 'listen' for the message using the JDBC Driver. I have used this method to push changes out to my application vs. polling. If you are using a Java database (H2) you have additional options. In my current application (SIEM) I have triggers in H2 that publish change events using JMX.