Springjdbc Analytic 2-execute method

Source: Internet
Author: User
Tags assert call back stmt

Everyone has used the JdbcTemplate Execute method, execute acts as the core portal of database operations, encapsulates the same steps for most database operations, and uses parameters PreparedStatementCallback callbacks for personalized operations.

 Public<T> T Execute (PreparedStatementCreator psc, preparedstatementcallback<t>action)throwsDataAccessException {assert.notnull (PSC,"PreparedStatementCreator must not being null"); Assert.notnull (Action,"Callback object must not being null"); if(logger.isdebugenabled ()) {String SQL=GetSQL (PSC); Logger.debug ("Executing prepared SQL statement" + (SQL! =NULL? "[" + SQL + "]": "")); }      //Get database connectionConnection con =datasourceutils.getconnection (Getdatasource ()); PreparedStatement PS=NULL; Try{Connection Contouse=con; if( This. nativejdbcextractor! =NULL&& This. Nativejdbcextractor.isnativeconnectionnecessaryfornativepreparedstatements ()) {Contouse= This. Nativejdbcextractor.getnativeconnection (Con); } PS=psc.createpreparedstatement (Contouse); //apply user-defined input parametersApplystatementsettings (PS); PreparedStatement Pstouse=PS; if( This. nativejdbcextractor! =NULL) {Pstouse= This. Nativejdbcextractor.getnativepreparedstatement (PS); }          //Call back functionT result =action.doinpreparedstatement (Pstouse);          Handlewarnings (PS); returnresult; }      Catch(SQLException ex) {//releasing a database connection avoids potential connection pool deadlocks when the exception converter is not initialized        if(PSCinstanceofParameterdisposer)          {(Parameterdisposer) PSC). Cleanupparameters (); } String SQL=GetSQL (PSC); PSC=NULL;          Jdbcutils.closestatement (PS); PS=NULL;          Datasourceutils.releaseconnection (Con, Getdatasource ()); Con=NULL; ThrowGetexceptiontranslator (). Translate ("PreparedStatementCallback", SQL, ex); }      finally {          if(PSCinstanceofParameterdisposer)          {(Parameterdisposer) PSC). Cleanupparameters ();          } jdbcutils.closestatement (PS);      Datasourceutils.releaseconnection (Con, Getdatasource ()); }  } 

The above methods encapsulate common operations, including the following:

    1. Get database connection
    2. Apply user-defined input parameters
    3. Call callback function
    4. Warning handling
    5. Resource release
Get database connection
 Public StaticConnection dogetconnection (DataSource DataSource)throwsSQLException {assert.notnull (DataSource,"No DataSource Specified"); Connectionholder Conholder=(Connectionholder) Transactionsynchronizationmanager.getresource (DataSource); if(Conholder! =NULL&& (conholder.hasconnection () | |conholder.issynchronizedwithtransaction ()))          {conholder.requested (); if(!conholder.hasconnection ()) {Logger.debug ("Fetching resumed JDBC Connection from DataSource");          Conholder.setconnection (Datasource.getconnection ()); }          returnconholder.getconnection (); }  Logger.debug ("Fetching JDBC Connection from DataSource"); Connection Con=datasource.getconnection (); //synchronization is supported by the current thread    if(Transactionsynchronizationmanager.issynchronizationactive ()) {Logger.debug ("Registering transaction synchronization for JDBC Connection"); //using the same database connection in a transactionConnectionholder Holdertouse =Conholder; if(Holdertouse = =NULL) {Holdertouse=NewConnectionholder (con); }          Else{holdertouse.setconnection (con); }          //Logging Database Connectionsholdertouse.requested (); Transactionsynchronizationmanager.registersynchronization (Newconnectionsynchronization (Holdertouse, DataSource)); Holdertouse.setsynchronizedwithtransaction (true); if(Holdertouse! =Conholder)          {Transactionsynchronizationmanager.bindresource (DataSource, holdertouse); }      }        returncon; }  

In terms of database connectivity, spring is primarily concerned with transaction-related processing. Based on the particularity of transaction processing,spring needs to ensure that the database operations in a thread are connected using the same transaction .

Apply user-defined input parameters
 protected  void  Applystatementsettings (Statement stmt) throws   SQLException { int  fetchsize = getfetchsize      ();  if  (fetchsize > 0 int  maxRows = Getmaxrows ();  if  (maxRows > 0

Setfetchsize is primarily designed to reduce the number of network interactions. When accessing resultset, it can incur significant overhead if it reads only one row of data from the server at a time. Setfetchsize means that resultset will get back the number of rows of data from the server at one time, so that at the next rs.next, it can fetch data directly from memory without the need for network interaction, improving efficiency. This setting may be ignored by some JDBC drivers and will cause memory to rise if the settings are too large. setMaxRows sets the maximum number of rows that can be contained by all ResultSet objects generated by this statement object to a given number.

Call callback function

Handle some of the general methods of personalization processing, that is, the callback of the Doinpreparedstatement method of the PreparedStatementCallback type parameter.

T result = Action.doinpreparedstatement (pstouse);

Warning handling
protected voidHandlewarnings (Statement stmt)throwsSQLException {//only attempt to print log when set to ignore warning    if(Isignorewarnings ()) {if(logger.isdebugenabled ()) {//Print Log If log is turned onSQLWarning Warningtolog =stmt.getwarnings ();  while(Warningtolog! =NULL) {Logger.debug ("SQLWarning ignored:sql State" + warningtolog.getsqlstate () + "', error code '" +Warningtolog.geterrorcode ()+ "', message [" + warningtolog.getmessage () + "]"); Warningtolog=warningtolog.getnextwarning (); }          }      }      Else{handlewarnings (stmt.getwarnings ()); }  }  

Here, a class sqlwarning,sqlwarning is used to provide exceptions to the database access warning information. These warnings are linked directly to the object that is the method that caused the report warning. warnings can be obtained from connection, statement, and ResultSet objects. attempting to get a warning on a connection that has been closed causes an exception to be thrown. Similarly, attempting to get a warning on a statement that has been closed or on a result set that has been closed will also cause an exception to be thrown. Note that closing a statement also closes the result set that it might produce.

The most common warning datatruncation:datatruncation directly inherits SQLWarning, which, for some reason, unexpectedly truncates the data value when the exception is reported as a datatruncation warning. The warning is handled in a way that does not throw an exception directly, and a warning is likely to result in data errors, but it does not necessarily affect program execution, so users can set their own way of handling warnings, such as ignoring warnings by default, printing only warning logs when a warning occurs, and only throwing exceptions directly in the other way.

Resource release

The connection to the database is not a direct call to the close () method in the connection API. Given the existence of a transaction, if there is a transaction in the current thread, then there is a connection to the common database in the current thread, in which case the released method in Connectionholder is used to reduce the number of connections by one instead of the actual free connection.

 Public Static voidDoreleaseconnection (Connection con, DataSource DataSource)throwsSQLException {if(Con = =NULL) {          return; }      if(DataSource! =NULL) {          //A common database connection exists when a transaction exists in the current thread//Direct use of the released method in Connectionholder to reduce the number of connections by one instead of the realthe release linkConnectionholder Conholder =(Connectionholder) Transactionsynchronizationmanager.getresource (DataSource); if(Conholder! =NULL&&connectionequals (Conholder, con)) {              //it ' s the transactional Connection:don ' t close it. conholder.released (); return; }} logger.debug ("Returning JDBC Connection to DataSource"); //in this method, you determine whether you need to close the connection and then close it.docloseconnection (Con, dataSource); }  

Springjdbc Analytic 2-execute method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.