How to make a database listener with java?
This is what LISTEN/NOTIFY was created for.
The only drawback is that you will need to have some kind of background thread that polls the database on a regular basis to see if any notifications are available.
You can also use the code from the Postgres Wiki to have a starting point
Implementing Database Listener
As @a_horse_with_no_name points out, PostgreSQL supports asynchronous notification channels for just this purpose.
You should create a trigger, probably in plpgsql, on the table(s) you wish to monitor. This trigger fires a NOTIFY
when the table changes, optionally including the changed data its self.
The application LISTEN
s on the notification channel(s) and processes any asynchronous notifications it receives.
Note that it's valid to send an empty query, and you should do that instead of SELECT 1
. e.g.:
stmt.execute("");
IIRC even that's optional if you're not using SSL, there's a way to poll purely client side. I don't remember what it is, though, so that's not real helpful.
You can determine exactly what changed by using a trigger-maintained change list table, or by using payloads on your notifications. Or you can simply re-read the whole table if it's small.
Related Topics
Does a Tcp Socket Connection Have a "Keep Alive"
How to Have Explained the Difference Between an Interface and an Abstract Class
Does Setting Java Objects to Null Do Anything Anymore
Connect 4 Check for a Win Algorithm
Comparing Two Java.Util.Dates to See If They Are in the Same Day
Java: Detect Duplicates in Arraylist
Best Java/Swing Browser Component
What Is the Maven-Shade-Plugin Used For, and Why Would You Want to Relocate Java Packages
Best Way to Represent a Fraction in Java
How to Implement a Db Listener in Java
How to Select a Dropdown Value in Selenium Webdriver Using Java
How to View the SQL Queries Issued by JPA
How to Serve .HTML Files with Spring
Can Java Call Parent Overridden Method in Other Objects But Not Subtype