Cascade tree structure, when deleted, need a first-level search, and first-level delete operations, so repeated operations, need to constantly call the same function, so it is very convenient to use recursive operation
The recursive function needs to be written separately and called in the method.
The following sample code, for a cascade delete, has a parent ID and then constantly looks for its child ID and removes the Child ID deletion through the child ID to continue looking for its ID, because of the multi-statement operation, so the thing is used to manually submit the way
(where the handling of abnormal mode is not rigorous!!) )
/** * Cascade deleted recursive function * @param conn callers need to pass their connection object in, convenient things operation * @param ID will delete the parent ID passed in * @throws Exception */Pub LIC void Dodel (Connection conn,int ID) throws exception{//find ID for delete operation String sql = "Delete from address where ID = ?"; PreparedStatement PS = conn.preparestatement (sql);p S.setint (1, id);p s.executeupdate (); Look for this ID as the parent ID for its child ID (cascade) SQL = "SELECT ID from address where parentid =?"; PS = conn.preparestatement (sql);p S.setint (1, id); ResultSet rs = Ps.executequery ();//This condition can end recursively when there is no data, and then jumps out, ending the loop while (Rs.next ()) {//here by passing in its child ID Then constantly find its descendants ID for deletion and query delete reciprocating operation This.dodel (Conn,rs.getint ("id"));} RS PS each recursive function call is created, so run out//for connection is called function incoming, cannot be closed, to use this connection to commit and ROLLBACK TRANSACTION rs.close ();p s.close (); }protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/ /TODO auto-generated method Stubresponse.setcontenttype ("Text/html;charset=utf-8"); Response.setcharacterencoding ( "Utf-8"); Proxydao proxy = new Proxydao (); int id = integer.parseInt (Request.getparameter ("Id")); Connection conn = Proxy.getconn (); try{//here because it is a multi-statement operation, consider the exception problem, you need to set the manual commit Conn.setautocommit (FALSE);//Call the recursive function, And pass in the current connection with the current Idthis.dodel (conn, id);//If normal operation no exception, this method will be called, COMMIT transaction Conn.commit ();} catch (Exception ex) {try {//If an exception occurs, the thing rolls back Conn.rollback ();} catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Ex.printstacktrace ();} Business processing completed, other operations ...
Code that uses recursive cascade removal