开发者

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 bec开发者_JAVA技巧ause 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.


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.)


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.


Your situation sounds ideal for the L2 cache since your objects rarely change and set your expulsion policy accordingly to refresh. Further if ALL mods are done through Hibernate then you can keep track of what happens through the events/interceptor infrastructure. Of course, any auxiliary tables Hibernate does not know about would have to be tracked by other means like how @BalusC suggested.


It seems that easiest approach to this is a trigger on the database end instead inside of your application. But this depends of course on the underlying database and if you really want to use SQL if everything else is done by Hibernate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜