开发者

Java Hibernate + Oracle 11.2 Locking

开发者 https://www.devze.com 2023-04-11 19:39 出处:网络
I need to synchronize my user table with repository(the other DB) during application startup. I have two Tomcat nodes with Apache mod_jk. So when I restart both of them I make double inserts and doubl

I need to synchronize my user table with repository(the other DB) during application startup. I have two Tomcat nodes with Apache mod_jk. So when I restart both of them I make double inserts and double updates. It seems like: T1 begin T2 begin T1 read the data T2 read the data T1 modify the data T2 modify the same data T1 insert T2 insert T1 commit T2 commit

When T1 modifies the data and then T2 modifies the same data I have lost update. And of course I have duplicates during insert operation. How should I do the synchronization?

  1. I suppose I can lock all the table using "select * for update" (for instance) and perform two synchronizations. One full and the other one empty.
  2. I can create special table for this and put STATUS colum there. When one node starts it performs SELECT FOR UPDATE of the开发者_Python百科 STATUS field and changes it to "RUNNING". When the other transaction reads the STATUS it doesn't perform synchronization if it's set to "RUNNING".

What's the best solution? Any other suggestions. Thanks!


The problem is that server startup doesn't mean application startup if more than one server is used to host the application.

If you always start and stop both servers at the same time, just configure only one of them (via a config parameter in the web.xml file, or a system property) to perform the synchronization.

If every server can be started and stopped independently, then I would not do anything at startup, but rather implement it as an administration use-case of the application, and trigger it on-demand, from the outside.


Configure one server so that it does not do the synchronisation - just as JB Nizet said. In our project we use Spring profiles.

Anyway, you should not get duplicates if you defined a unique index on a business key. You can get rid of Oracle's lost updates using optimistic locking in Hibernate. A transaction would try to update a specific version (the one it read) and get an error if another transaction updated it with a new version counter.

0

精彩评论

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