简体   繁体   中英

How to get notified when auto-commit is performed on a Java connection?

I'm trying to figure out if there's a way to register to an auto-commit event.

Is there an observer? Perhaps I decorate an auto-commit connection or statement in order to be notified? What is the method to decorate?

I tried listening to Connection.commit() but it's not being invoked on statement executions.

Thanks. Alik.

auto-commit means that there is an implied commit at the end of each statement execution. As far as I know there is no event that you can listen to, and you cannot expect anyone to internally invoke Connection.commit() , because the auto-commit happens somewhere within the stack of the RDBMS that you are using, possibly even on the server.

So, in order to add an auto-commit event to JDBC you have to decorate every single function that may cause a statement to be executed, and see whether the SQL that was executed started with UPDATE , INSERT or DELETE verb. (Basically, anything but SELECT .)

The way I have decorated JDBC in the past is as follows:

  1. Make a copy of every single JDBC interface, create a class out of it, create a concrete function for each method which delegates to a reference to a JDBC interface. Use lots of search-and-replace or possibly an editor that supports recording and replaying macros for that.

  2. Define your own driver, and register it with JDBC, using your own driver name, like "jdbcdeco".

  3. Establish the following convention: the connection string of your driver will be "jdbcdeco:" followed by the connection string of the driver that you want to decorate. So, if the connection string of the connection that you want to decorate is "jdbc:mysql://localhost/test" then the following connection string must be specified: "jdbc:jdbcdeco:mysql://localhost/test"

  4. JDBC will instantiate your driver, and it will pass it the connection string, which begins with "jdbcdeco:" . You strip away the "jdbcdeco:" part, and you are left with another connection string, which you use to pass again to JDBC in order to create the actual connection that is going to be decorated.

Good luck, and have fun!

Short answer- no such way exists to register to hear on auto commit. As mentioned in the answer by Mike, if you want to capture every commit you need to write custom code, you have to make the call whether you want to go through that much effort or not.

A simpler workaround would be to setAutoCommit as off on your connection but that is not what you have asked for :).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM