Deep analysis of system architecture and mapping principle of IBATIS framework __ Frame

Source: Internet
Author: User
Tags reflection

The main class hierarchy of the IBATIS framework

Overall, the IBATIS system structure is relatively simple, it mainly completes two things: according to the JDBC specification to establish a connection to the database, through reflection through the Java object and the database parameter interaction between the transformation relationship.

IBATIS's frame structure also organizes the class hierarchy according to this idea, in fact it is a typical interactive framework. Prepare the necessary prerequisites for interaction, then build an interactive environment in which the interactive environment is divided into sessions, and each session has an environment. When all these environments are ready, the rest is the exchange of data. Actually involves the network communication, generally will be the similar processing way.

Figure 1 is the main class hierarchy diagram of the IBATIS framework:
Figure 1 The main class hierarchy diagram of the IBATIS framework

The left Sqlmapclient interface in the above class diagram mainly defines the client's action behavior including SELECT, INSERT, UPDATE, delete. The right side mainly defines the current client's execution environment on the current thread. Sqlmapsession can be shared or created by itself, and if it is created at the end you must call off the interface shutdown.

When the user holds the Sqlmapclientimpl object, he or she can use IBATIS to work. There is also a reference to another class Sqlmapexecutordelegate this class can be seen from the name of the execution proxy class. This class is important because he is coupled with the user-side execution and execution environment, and he holds the data needed to perform the operation while providing an environment for managing the Operation dependencies. So he's a strong coupling class, and it can be considered a tool class.

Back to the top of the page

Design strategy of IBATIS framework

IBATIS's main design goal is to make it easier to manage the input and output data when we execute SQL, so it is IBATIS's core competency to make it easy for us to write SQL and easily get the execution result of SQL. So IBATIS is how to achieve its core competitiveness.

An important part of the IBATIS framework is its sqlmap configuration file, Sqlmap the core of the configuration file is the Statement statement including Ciud. IBATIS gets all the Statement execution statements by parsing the Sqlmap configuration file, and forms the Parametermap, Resultmap two objects that are used to process the parameters and the SQL objects that are parsed and handed to the database for processing. This eliminates the connection to the database, and a SQL execution condition is already in place.

Figure 2 depicts the Statement-related class structure diagram:
Figure 2. Statement-related class structure diagram

Figure 2 shows the basic architectural relationships around SQL execution, but a key part is how to define the relationship between the parameters in the SQL statement and the Java object, which also involves a range of issues such as Java type to the conversion of the database type.

The general process of mapping data is this: the parameters are parsed according to the SQL statements defined in the Statement, stored in the Map collection in the order in which they appear, and the Java data type of the parameter is resolved according to the Parametermap object type defined in Statement. The Typehandler object is constructed according to its data type, and the replication of the parameter value is accomplished by Dataexchange object.

Figure 3 is a class structure diagram related to parameter mapping:
Fig. 3. Class structure diagram related to parameter mapping

Figure 3 is the mapping structure of the input parameters, and the mapping of the result resultmap is similar. The main thing is to resolve the relationship between the parameters in the SQL statement and the column names that return the results and the attributes in Parameterclass and ResultClass defined in Statement.

Back to the top of the page

Operation Principle of IBATIS frame

The previous general analysis of the structure of the main classes of the IBATIS framework, where the main look at how these classes are connected, how to work. Figure 4 depicts the main steps of execution of the entire process.
Figure 4.iBATIS Main steps to perform

The creation and release of the Sqlmapsession object described in the above figure varies according to circumstances, because Sqlmapsession is responsible for creating the connection to the database, including the management of the transaction, IBATIS can manage or be managed externally, IBATIS Your own management is implemented by sharing sqlmapsession objects, and multiple Statement are executed with a sqlmapsession instance and are thread-safe. If it is external program management, you should control the lifecycle of the Sqlmapsession object.

Figure 5 is a detailed sequence diagram that executes a Statement through Spring invocation IBATIS:
Figure 5. Spring calls IBATIS to execute a Statement sequence diagram

(See the clear version of Figure 5.) )

IBATIS's main work connection and interaction, so we must design different transaction environment according to the different transaction cost.

Back to the top of the page

Example

Below we will be based on a specific example of how a Statement to complete the mapping, we use a typical query to look at the data in the Java object how to assign to the parameters in the SQL, and then see how the SQL query results are translated into Java objects.

Take a look at some of the sample code and configuration file, the complete code look at the attachment.

Spring's applicationcontext configuration file:
Listing 1. Applicationcontext.xml

				
<beans> <bean id= "Sqlmaptransactionmanager" class= "Org.springframework.jdbc.datasource.DataSour Cetransactionmanager "> <property name=" dataSource "ref=" DataSource "/> </bean> <bean id=" Sqlmaptransactiontemplate "class=" Org.springframework.transaction.support.TransactionTemplate "> &LT;PR Operty name= "TransactionManager" ref= "Sqlmaptransactionmanager"/> </bean> <!--SQL Map--> <b Ean id= "sqlmapclient" class= "Org.springframework.orm.ibatis.SqlMapClientFactoryBean" > <property nam E= "Configlocation" value= "Com/mydomain/data/sqlmapconfig.xml"/> <property name= "DataSource" ref= "DataSource" /> </bean> <bean id= "DataSource" name= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSo"
        Urce "destroy-method=" Close "> <property name=" driverclassname "value=" Oracle.jdbc.driver.OracleDriver "/> <property Name= "url" value= "Jdbc:oracle:thin:@10.1.5.11:1521:xe"/> <property name= "username" value= "Junshan"/> 
    <property name= "Password" value= "Junshan"/> <property name= "maxactive" value= "/>" </bean> <bean id= "Accountdao" class= "Com.mydomain.AccountDAO" > <property name= "sqlmapclient" ref= "Sqlmapclie" NT "/> <property name=" sqlmaptransactiontemplate ref= "sqlmaptransactiontemplate"/> </bean> <
 /beans>

Here is a Statement of account.xml:
Listing 2. A Statement in Account.xml

				
<select id= "Selectaccount" parameterclass= "account" resultclass= "account" >
    select
      acc_id,
      acc_ First_Name as FirstName,
      acc_last_name as LastName,
      Acc_email as EmailAddress,
      acc_date from
    account< C10/>where acc_id = #id: integer# and acc_first_name = #firstName #
</select>

Here is the Java test class:
Listing 3. SimpleTest

				
public class SimpleTest {public static void main (string[] args) {ApplicationContext factory =
        New Classpathxmlapplicationcontext ("/com/mydomain/data/applicationcontext.xml");
        Final Accountdao Accountdao = (Accountdao) factory.getbean ("Accountdao");
        Final Account Account = new account ();
        Account.setid (1);
        Account.setfirstname ("Tao");
        Account.setlastname ("Bao");
        Account.setemailaddress ("junshan@taobao.com");
        Account.setdate (New Date ()); try {accountdao.getsqlmaptransactiontemplate (). Execute (new Transactioncallback () {public Object dointransaction (transactionstatus status) {try{Accountdao.dele
                            Teaccount (Account.getid ());
                            Accountdao.insertaccount (account);
                            Account.setlastname ("Bobo");
          Accountdao.updateaccount (account);                  Account result = Accountdao.selectaccount (account);
                            SYSTEM.OUT.PRINTLN (result);
                        return null;
                            catch (Exception e) {status.setrollbackonly ();
                        return false;
            }
                    }
                });
         Accountdao.getsqlmapclient (). CommitTransaction ();
         catch (Exception e) {e.printstacktrace ();
 }
     }
}

Back to the top of the page

The parsing of SQL statements by IBATIS

The SQL parsing described here is only for the SQL statements defined in the IBATIS configuration file, as shown in Listing 2 in the previous section. Unlike a standard SQL statement, the assignment of a parameter is the variable name of the "#" package. How to parse this variable is the work that IBATIS to do. Of course, there are many other forms of SQL expression, such as dynamic SQL.

Now what we care about is when we execute:
Listing 4. Executing Query methods

				
Accountdao.selectaccountbyid (account) 

IBATIS will parse it by selecting the Statement in Listing 2, which will eventually parse it into a standard SQL submission to the database execution and set two selection criteria parameters. What is the detail of the parameter mapping in this process?

As explained in the previous second section, IBATIS will parse the Sqlmap configuration file into Statement, including Parametermap, Resultmap, and parsed SQL. When IBATIS build a good requestscope execution environment, the work to do is to send the object data in conjunction with Parametermap extract an array of parameters, the order of the array corresponds to the order of the parameters in SQL, and then call Preparedstatement.setxxx (i, parameter) submit parameters.

In Listing 3, we assign the id attribute and the FirstName property of the account object to 1 and "Tao," and when the code in Listing 4 is executed, IBATIS must pass the two property values to the parameters of the object in the SQL statement in Listing 2. How this is done, in fact, is very simple, in Figure 3, describes the relationship of the Parametermap-related classes, all of which have saved all the necessary information in Sqlmap configuration file initialization to parse Statement in Listing 2, and the specific information is as follows:

The final SQL statement is:
Listing 5. Parsed SQL

				
Select
    acc_id,
    acc_first_name as FirstName,
    acc_last_name as LastName,
    Acc_email as EmailAddress, Acc_date from the account
where acc_id =? and Acc_first_name =? 

#id: integer# will be resolved to the JDBC type is INTEGER and the parameter value takes the id attribute of the account object. #firstName # is also parsed into the FirstName attribute of the account object, while parameterclass= "Account" indicates the class type of account. Note #id in Listing 5: integer# and #firstName # are replaced with ". ", IBATIS how to guarantee their order. In parsing Listing 2, IBATIS takes a valid variable name from the "#" delimiter to build the Parameter object array, which is the order in which the variables appear in the SQL. IBATIS then creates the appropriate Dataexchange and Parameterplan objects based on these variables and the type specified by Parameterclass. The list of setter and getter methods for variables is saved in the Parameterplan object in the previous order.

So the parameter assignment is based on the list of getter methods saved in Parameterplan and the account object that is passed in, using the reflection mechanism to get an array of parameter values corresponding to listing 5, and then submitting the array to the database according to the specified JDBC type. These processes can be clearly described in the sequence diagram in Figure 6:
Figure 6. Mapping parameter values to database procedure sequence diagram

The Preparedstatement.setnull (i, Jdbctype) is set when the value is empty in the 8 step in Figure 4 above if the variable in Listing 2 does not have the Jdbctype type set, there may be an error.

Back to the top of the page

Database fields are mapped to Java objects

After the database executes the SQL, it returns the results of the execution, and in the example in section 4th, there are two messages with ID 1, firstName as "Tao", IBATIS How to set the two records to the account object.

Like Parametermap, the resources needed to populate the returned information are already contained in Resultmap. When a ResultSet object is saved that returns the result, the column name is mapped to the corresponding property of the account object. This process is generally as follows:

This is the account object, based on the resultclass that is defined in Resultmap to create the returned object. Gets a property array of all the writable methods of this object, then matches the previous array of attributes according to the column names in the returned ResultSet, and constructs the matching result into a set (Resultmappinglist) followed by the selection of the Dataexchange type , the Accessplan type provides support for the real data exchange that follows. The order of the Array (columnvalues), which is the order of the corresponding column names in the SQL, is made up of the values of the columns corresponding to the Resultmappinglist collection from the ResultSet. Finally, the setter method that calls the Columnvalues value to the property of the account object is set to the object. This process can be expressed in the following sequence diagram:
Figure 7. Mapping return object sequence diagram

Back to the top of the page

The results of the sample run

The first two subsections describe the mapping principle of input parameters and output results, and then analyze the results of the execution of listing 3 code with the example in section 4th.

The result of executing the code shown in Listing 3 is:
Listing 6. Running results of the sample program

				
Account{id=0, Firstname= ' Tao ', Lastname= ' Bobo ', emailaddress= ' junshan@taobao.com '}

The above results seem to be different from what we expected, and the values we insert into our database are {1, "Tao", "Bao", "junshan@taobao.com", "Time"}, followed by the query in Listing 2. The return should be the same result. The result of the ID is incorrect and the date property value is missing. Take a closer look at Listing 2, this Statement can find that the column names that return the results are {acc_id,firstname,lastname,emailaddress,acc_date} where IDs and DATE do not map to the attributes of the account class 。 The ID is assigned the default number 0, and date is not assigned a value.

Another notable place is the variable ID followed by the JDBC type, and this JDBC type is useless. Usually it's not used, so you can not set it, IBATIS automatically chooses the default type. But if you want this, this value may be empty. If you do not specify a JDBC type, it may be problematic to work correctly in Oracle, but it can cause Oracle to have multiple compilations of this current SQL, which can affect the performance of the database. And when the same Java type can save different values to the database by specifying the JDBC type if it corresponds to multiple JDBC types (such as Date corresponds to a JDBC type with java.sql.Date, Java.sql.Timestamp).

Back to the top of the page

Summarize

If you use the simplest words to summarize the main features of IBATIS, I think the following code is sufficient to generalize.
Listing 7. Typical Java operations database code

				
Class.forName ("Oracle.jdbc.driver.OracleDriver"); 
Connection conn= drivermanager.getconnection (url,user,password);
java.sql.PreparedStatement  st = conn.preparestatement (SQL);
St.setint (0,1);
St.execute ();
Java.sql.ResultSet rs =  st.getresultset ();
while (Rs.next ()) {
    String result = rs.getstring (colname);
}

IBATIS is to break up these lines of code, but the final execution is still the lines of code. The first two lines are the management of the data source for the database, including transaction management, 3, 42 rows IBATIS the configuration file to manage SQL and the mapping of input parameters, 6, 7, 8 rows are iBATIS to get back the results to the Java object mapping, he is also through configuration file management.

The configuration file corresponds to the corresponding code as shown in the figure:
Figure 8. The configuration file corresponds to the corresponding code

IBATIS to achieve the goal is to put the user care and easy to change the data into the configuration file configuration, user-friendly management. And the process of the fixed-invariant to IBATIS to achieve. This is the user to operate the database is simple, convenient, this is also the value of IBATIS.

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.