简体   繁体   中英

How to cancel a running SQL query?

I know that statement.cancel() can be used to cancel a running SQL query, but what I want to know is, how will I get hold of this statement object in another thread.

Use case:

  • I request to start a thread that runs a statement.
  • Then from a separate request(another thread) I might want to cancel this thread.

How in this new request will I get the statement to call the cancel method in it.

There might be cases when there will me more than one statements running.

Additional information, it is a web application, using spring framework, hibernate and JPA. Now in the UI there are 2 buttons, Button 1 will trigger the SQL query and button 2 has to cancel that query

I referred to this example but it uses the same thread to call the new thread, which I cannot do.

This is how the query is started:

    Query query = mEntityManager.createNativeQuery(globalQuery.toString());
    List<Object[]> results = query.getResultList();

Edit:

  1. One way I can think of is to keep track of all the running statements and then find the one for which the SQL statement has to be cancelled.

There are two different sessions that will help you:

If you want to exchange an object like your statement between two requests from the same user, independent if these requests run in parallel or one after another, you usually store them in the HttpSession of the HttpServletRequest .

And you can use the Session of Hibernate to cancel the current query:

public void startLongRunningStatement() {
  EntityManager entityManager = ...

  // Aquire session
  Session hibernateSession = ((HibernateEntityManager) em.getDelegate()).getSession();

  // Store the HibernateSession in the HttpSession
  HttpSession httpSession = servletRequest.getSession()
  httpSession.setAttribute("hibernateSession", hibernateSession);

  try {
    // Run your query  
    Query query = mEntityManager.createNativeQuery(globalQuery.toString());
    List<?> results = query.getResultList();

  } finally {
    // Clear the session object, if it is still ours
    if (httpSession.getAttribute("hibernateSession") == hibernateSession) {
      httpSession.removeAttribute("hibernateSession");
    }
  }
}

public void cancel() {
  // Get the Hibernate session from the HTTP session
  HttpSession httpSession = servletRequest.getSession()
  Session hibernateSession = (Session) httpSession.getAttribute("hibernateSession");
  if (hibernateSession != null) {
    // Cancel the previous query
    hibernateSession.cancelQuery();
  }

}

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