问题
I have a Java SE application using JPA provided by Hibernate and a HSQL database. The application queries the database with EntityManagers for information in order to draw charts on the screen. While the query is executing, the area for the chart has the typical spinning icon to let the user know that it's working. Some queries take a long time, and I want to have the feature to abort/cancel the query. I know I can unwrap the EntityManager and get the Hibernate Session and call cancelQuery(), but that doesn't do anything because the HSQLDB driver doesn't support the cancel() method on the Statement interface (http://hsqldb.org/doc/2.0/apidocs/org/hsqldb/jdbc/JDBCStatement.html#cancel()). Is there another way either through API or redesigning my app? Not being able to cancel a running query is a nuisance.
回答1:
At the Moment there is no way to end a long-running Statement on a HSQLDB Server. The ALTER SESSION Method provided by Fredt does not seem to work in the current RC2 for 2.3.4 (and also in the svn revision 5511), it just leads to a transaction rollback:serialization failure AFTER the select statement has finished working. So the only way to deal with this Problem is setting the Timeout. This is not an actual Solution to the Problem, though.
Update: In the newest Version of HSQLDB in the SVN Repository (Rev. 5627) and in the upcoming 2.3.4 Release, the possibility to cancel a statement immediately is now implemented. There also is a new Method, ALTER SESSSION END STATEMENT, that can abort a transaction without a rollback. See https://sourceforge.net/p/hsqldb/bugs/1436/ for details.
回答2:
You can use a separate connection with admin rights and terminate the transaction in a different session:
ALTER SESSION <session number> RELEASE
http://hsqldb.org/doc/2.0/guide/sessions-chapt.html#snc_statements
In the latest Subversion revisions of HSQLDB, this statement also terminates any SELECT statement that is running in the target session.
You can use SESSION_ID() to find the id of the session and use it to release the session.
Also, it is possible to use JDBCStatement.setQueryTimeout(n) before you execute the query.
The cancel() method may be supported in the near future.
来源:https://stackoverflow.com/questions/34094074/how-to-abort-cancel-hsqldb-query