1 Public intAdd (SalesOrder so) {2 intOrderId =-1;3DB db =NewDB ();4Connection Connection =db.getconn ();5 BooleanAutocommit =true;6 Try {7Autocommit = Connection.getautocommit ();//The default submission method is first written down to restore the site8Connection.setautocommit (false);9}Catch(SQLException E1) {Ten //TODO auto-generated Catch block One e1.printstacktrace (); A } -String sql = "INSERT into SalesOrder (uid,status) VALUES (?,?)"; - Try { the //Order Write Database -PreparedStatement PS =connection.preparestatement (SQL, -Statement.return_generated_keys);//get an auto-generated ID for an order while adding an order -Ps.setint (1, So.getcustomer (). Getcid ()); +Ps.setint (2, So.getstatus ()); - ps.executeupdate (); + A //get a new automatically generated order number atResultSet Rskey =Ps.getgeneratedkeys (); - Rskey.next (); -OrderId = Rskey.getint (1); - - //Write all order items to the database -String Sqlitem = "INSERT into Salesitem (pid,pcount,oid) VALUES (?,?,?)"; inPreparedStatement Psitem =connection.preparestatement (sqlitem); -list<salesitem> items =So.getitems (); toIterator<salesitem> it =items.iterator (); + while(It.hasnext ()) { -Salesitem item =It.next (); thePsitem.setint (1, Item.getitem (). GetProduct (). Getpid ()); *Psitem.setint (2, Item.getitem (). GetCount ()); $Psitem.setint (3, orderId);Panax NotoginsengPsitem.addbatch ();//Adding Each order item add action to a batch job - } thePsitem.executebatch ();//perform batch processing +Connection.commit ();//submit a database manually A ps.close (); the psitem.close (); + -}Catch(SQLException e) { $ Try { $ Connection.rollback (); -}Catch(SQLException E1) { - e1.printstacktrace (); the } - e.printstacktrace ();Wuyi}finally { the Try { - Connection.setautocommit (autocommit); Wu connection.close (); - db.close (); About}Catch(SQLException e) { $ e.printstacktrace (); - } - } - returnorderId; A}
The purpose of this is to add the purchase item to the order only after we have successfully added the new order. To keep the data consistent
Ps:
The purpose of commit is to submit the cache to the repository.
Autocommit=true is that you do not have to perform a commit, and the program will automatically help you execute it.
Autocommit=false, until you commit or disconnect commit.
JSP---Online shop, manually commit transactions to ensure data consistency