Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to observe change in Database table through Hibernate?

In my application, I am storing a small table containing 50 records in a singleton class because the data in this table hardly changes - e.g. the list of countries.

Although, the concept is not good, I have to continue with it right now. Is there any solution in Hibernate which observe change in the table and on change, invoke a method of a class to update the variable.

like image 657
Shashi Avatar asked Sep 18 '25 05:09

Shashi


2 Answers

Hibernate won't get notified of changes made at the table level. The (bad) solution would be to update the data through Hibernate's API and to use one of the callback provided by an Interceptor to do some black magic voodoo with the Singleton. But honestly, the (right) way to handle this would be to get rid of that singleton and to put the data in 2nd level cache (and to invalidate the cache if you update the table manually).

(EDIT: As ChssPly76 mentioned in a comment, there is an intermediary solution if removing the singleton is not an option which consists in modifying the singleton to find and return cached hibernate-managed entities like your countries for example.)

like image 75
Pascal Thivent Avatar answered Sep 19 '25 19:09

Pascal Thivent


Implement Interceptor#onFlushDirty(). Ah no, you want to do it from the other side on. No, it's not possible. Best what you can do is to reload the data at certain intervals, for example once every hour. You can use java.util.TimerTask for this.

That said, a Singleton is really a bad idea. Just have it as some kind of an attribute of the main context. If it is for example an Java EE webapplication, you can use ServletContext for this.

like image 27
BalusC Avatar answered Sep 19 '25 19:09

BalusC