IBatis 2.x and MyBatis 3.0.x differences (from IBatis to MyBatis)

Source: Internet
Author: User
Tags sql using

From IBatis to MyBatis, are you ready?

For developers working with Java EE, IBatis is a familiar persistence layer framework, and ibaits is essentially the choice for a durable layer framework before a one-stop object/relational mapping (O/R Mapping) solution in Hibernate and JPA prevails. Even in the endless framework of the persistent layer of today, iBatis with easy to learn, easy to use, lightweight and flexible, but also still have a place. Especially for developers who are good at SQL, IBatis's direct support of SQL and stored procedures allows them to gain the IBatis encapsulation advantage without losing the means of SQL tuning, which HIBERNATE/JPA can not match. In particular, the main advantages of using the IBatis framework are the following:

First, the IBatis encapsulates the vast majority of the JDBC boilerplate code, allowing the developer to focus on the SQL itself without having to spend the effort to process such as registering the driver, creating the Connection, and making sure that the Connection is turned off in such cumbersome code.

Second, IBatis can be considered as the lowest-cost, easiest-to-get-to-learn framework in all the mainstream persistence frameworks. While other persistent layer frameworks are known to be low-threshold, easy to use, but when you really used it will find that it is very difficult to master and good at it. I need to be in the job interview often, I have heard a lot of applicants describe, their project in the technology selection of Hibernate, and later found difficult to control, have to code with JDBC or IBatis rewrite.

IBatis has been honored by thousands of Java developers since it was released on the Apache Software Foundation website, with his star brothers (Http server,tomcat,struts,maven,ant, etc.). However, in mid-June this year, almost 3.0 versions were released, and a statement on IBatis's homepage, "Apache IBatis has been retired", caused a flurry of waves in the community. After six years of Apache sojourn, IBatis is hosting code to Google. The main reason given in the statement is that, compared to Apache, Google Code is more conducive to developer collaboration and more adaptable to rapid release. At the same time, IBatis changed its name to MyBatis.

From IBatis to MyBatis, not just on name changes, MyBatis provides more powerful functionality without losing its ease of use, but in many places it has been simplified with the help of JDK generics and annotation features. IBatis really should retire, because a better successor, after 10 Beta releases, is already in front of us.

This paper will mainly focus on the changes of MyBatis and IBatis, so as to facilitate the smooth transition from IBatis to MyBatis.

Back to top of page

Start with a MyBatis example

If the reader is exposed to some common Java EE frameworks, it should be known that these frameworks need to provide a global configuration file that specifies the settings and parameter information required for the program to function properly. For commonly used persistence layer frameworks (Hibernate, JPA, IBatis, etc.), you typically need to configure two types of files: one for specifying data sources, transaction properties, and some other parameter configuration information (usually a separate file, which can be called a global profile), and the other for Specifies the mapping information between database tables and programs (possibly more than one file, which we call a mapping file). MyBatis is no exception, although part of it can be done in the form of annotations, but these two parts of the content itself is still essential.

According to IBatis habits, we usually name the global configuration file Sqlmapconfig.xml, the file name itself is not required, in MyBatis, the file is often named Configuration.xml (after reading the full text, readers may find that in IBatis often appear in the "Sqlmap" in the MyBatis is gradually diluted, in addition to this, but also for example iBatis configuration file root element is <sqlmapconfig>, specify the element of the map file is <sqlmap> Sqlmapclient and so on, this change is to show that IBatis is only a framework based on SQL mapping, and in MyBatis in the Mapper, Session, Configuration and other commonly used ORM framework of the name instead, It is nothing more than two things: first, to reduce the cost of learning that developers are switching frames, and secondly, MyBatis fully absorbs the good practices of other ORM frameworks, and MyBatis is now more than just a SQL mapping framework. The information that can be configured in the global configuration file mainly includes the following aspects:

    • The properties---is used to provide property information that consists of a series of key-value pairs that can be used throughout the configuration file.
    • The settings---is used to set the run-time mode of the MyBatis, such as whether lazy loading is enabled or not.
    • Typealiases---Specify an alias for the Java type, you can replace the fully qualified name of the Java class with an alias in the XML file.
    • Typehandlers---The type processor for a particular type is executed when MyBatis sets a value for the placeholder by PreparedStatement or when the value is fetched from ResultSet.
    • Objectfactory---MyBatis to create a result object by Objectfactory. You can implement your own Objectfactory class by inheriting defaultobjectfactory.
    • The plugins---is used to configure a series of interceptors to intercept the execution of mapped SQL statements. You can implement your own interceptors by implementing the Interceptor interface.
    • Environments---Used to configure Data source information, including connection pooling, transaction properties, and so on.
    • All SQL mapping files used in the mappers---program are listed here, and these mapped SQL are MyBatis managed.

Most of the elements mentioned above are not required, and typically MyBatis provide default values for elements that do not have an explicit setting. An example of a simple global configuration file is as follows:

Listing 1. Simple global configuration File example
 <?xml version= "1.0" encoding= "UTF-8"?> <!--IBatis and MyBatis global profiles use different DTD constraints when applying You need to be aware when upgrading from IBatis to MyBatis (the mapping file DTD constraints are not the same)-and <!  DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration> <!--configuration data source related information--<environments default= "Demo" > <environment id= "Demo" > < TransactionManager type= "JDBC"/> <datasource type= "Pooled" > <property name= "Driver" value= .../> <prop Erty name= "url" value= .../> <property name= "username" value= "root"/> <property name= "password" value= "root"/  > </dataSource> </environment> </environments> <!--list map files--<mappers> <mapper Resource= "Footmark/mybatis/demo/userinfomapper.xml"/> </mappers> </configuration> 

With this information, MyBatis can establish a connection to the database and apply the given connection pool information and transaction properties. MyBatis encapsulates these operations and eventually exposes a sqlsessionfactory instance for developers to use, as the name implies, a factory class that creates sqlsession, and through sqlsession instances, the developer is able to manipulate the business logic directly, You do not need to write JDBC-related boilerplate code repeatedly. The code to generate sqlsession based on the global configuration file is as follows:

Reader reader = Resources.getresourceasreader ("Configuration.xml");  Sqlsessionfactory sqlsessionfactory =  new Sqlsessionfactorybuilder (). build (reader);  Sqlsession sqlsession = Sqlsessionfactory.opensession ();

You can think of the above three lines of code as the boilerplate code that MyBatis creates sqlsession. Where the first line of code loads the configuration file on the classpath, resources is a tool class provided by MyBatis, which is used to simplify the loading of resource files, which can access files of various paths, but the most common example of this is a classpath-based representation. If the reader is aware of Hibernate, it will be found that MyBatis, regardless of the use of style or class name and Hibernate very similar, I have many times in the Java community at home and abroad to see someone said MyBatis in the HIBERNATE/JPA closer. Regardless of whether this is true, the persistence of technology in a vigorous competition and development, eventually in the community to form a unified understanding and widely accepted, which is not necessarily a good thing for developers, MyBatis at this point is only to the de facto standard step closer.

After the global configuration file has been completed and the Sqlsession object is obtained through MyBatis, data access operations can be performed. For Ibatis/mybatis, the operation to be performed is actually the SQL statement that is configured in the mapping file. The configuration is basically the same, as follows:

Listing 2. To configure SQL statements in a mapping file
<?xml version= "1.0" encoding= "UTF-8"?> <!  DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  <mapper namespace= "Mybatis.demo.UserInfoMapper" >  <select id= "Selectuser" parametertype= "int" Resulttype= "Mybatis.demo.UserInfo" >  select * from UserInfo where UserID =#{userid}  </select>  </mapper>

In IBatis, namespace is not required, and its existence has no practical meaning. In MyBatis, namespace finally comes in handy, which makes mapping files and interface bindings very natural. There is a special description of the interface bindings later. The way to execute SQL using sqlsession is as follows:

Listing 3. Using Sqlsession to execute SQL statements configured in the mapping file
Try  {  UserInfo UserInfo = (UserInfo) sqlsession.selectone  ("Mybatis.demo.UserInfoMapper.getUser", 2);  System.out.println (userinfo);  } Finally  {  sqlsession.close ();  }

It is important to note that the use of sqlsession must conform to the above format, which is to close it in the finally block. To ensure that resources are released to prevent memory leaks!

The above is a simple and complete MyBatis program. It involves four steps such as global configuration file, mapping file, building Sqlsession object, performing data access operation. The following will decompose three blocks of content in addition to building sqlsession objects.

Back to top of page

MyBatis changes to the global configuration file

The main elements of the MyBatis global configuration file are basically the same as the IBatis, and are only adjusted for usage and individual names. The meaning of the element is no longer described, and the main differences between the IBatis and MyBatis configuration files are explained below.

First, the DTD constraints of the two versions are different, and the MyBatis DTD file is already included in the Mybatis-3.0.x.jar package under the release package. What this directly affects is that the root element of the IBatis configuration file is <sqlmapconfig>, while MyBatis is using <configuration>.

Second, the usage of,<settings> has changed, before the format is:

Listing 4. How to set properties in IBatis
<settings props1= "value1" props2= "value2" .../>

The property to set is directly in the form of a key-value pair as a <settings> property. And in the MyBatis, adjust to a slightly more complex but more organized way:

Listing 5. How to set properties in MyBatis
<settings>  <setting name= "Props1" value= "value1"/>  <setting name= "props2" value= "value2"/ > ... </settings>

In addition, you previously configured the transaction manager and the data source in the following ways:

Listing 6. How to configure the transaction manager and data sources in IBatis
<transactionmanager type= "jdbc" >  <datasource type= "simple" >  <property name= "jdbc. Driver "value=" ${driver} "/>  <!--Other data source information omitted--  </dataSource>  </transactionmanager >

Adjust the MyBatis in the following way:

Listing 7. How to configure the transaction manager and data sources in MyBatis
<environments default= "Demo" >  <environment id= "Demo" >  <transactionmanager type= "JDBC"/>  <datasource type= "Pooled" >  <property name= "JDBC. Driver "value=" ${driver} "/>  <!--Other data source information omitted--  </dataSource>  </environment>  </environments>

Data source management through <environments> is primarily to simplify switching between multiple sets of data source configurations, such as development and distribution using different configurations.

Finally, the mapping file is specified in IBatis as follows:

Listing 8. How to specify the mapping file in IBatis
<sqlmap resource= .../> <sqlmap resource= .../> <sqlmap resource= .../>  

In MyBatis, adjust to the following way:

Listing 9. How to specify the mapping file in MyBatis
<mappers>  <mapper resource= .../>  <mapper resource= .../>  </mappers>

The main starting point for these tweaks is not to make MyBatis more powerful, but to make the configuration more reasonable and easier for developers to read and understand.

So far, we've focused on global configuration in XML form, which is not the only option, MyBatis also provides a way to configure it through code:

Listing 10. Configuring with code in MyBatis
DataSource ds = ...//get a DataSource  transactionfactory txfactory = new Jdbctransactionfactory ();  Environment env = new Environment ("Demo", Txfactory, DS);  Configuration cfg = new configuration (env);  Cfg.addmapper (userinfomapper.class);  Sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). build (CFG);

Combined with the previous configuration file, it is easy to understand the meaning of this code, so don't repeat it. However, it is important to note that the Addmapper () method of the Configuration, the parameters of the method is usually an interface, you can define several methods in the interface, using annotations on the method to specify the mapped SQL statement. A typical interface definition and the corresponding data access methods are as follows:

Listing 11. To bind a mapped SQL statement to a method in an interface
Map SQL Binding Interface public interface Userinfomapper  {  @Select ("select * from userinfo where UserID = #{userid}")  PU Blic UserInfo getuserinfo (int userid);  }  The data access method that corresponds to the interface binding is try  {  //userinfo UserInfo = (UserInfo) sqlsession.selectone  (" Mybatis.demo.UserInfoMapper.selectUser ", 2);  Userinfomapper userinfomapper =  sqlsession.getmapper (userinfomapper.class);  UserInfo UserInfo = userinfomapper.getuserinfo (1);  System.out.println (userinfo);  } Finally  {  sqlsession.close ();  }

Back to top of page

Changes to the MyBatis mapping file

MyBatis There are many places to format the map file, but most of it is just a change in the name, and the modern IDE supports the associative function, which makes it easy to get to the elements and properties of the current position. So this basically does not cause any trouble to the developer.

For the mapping file, the first is a series of property name changes, these are simply name changes, usage and meaning has not changed:

    • As with the global configuration file, the root element is also adjusted to <mapper> from the original <sqlMap> due to changes in the DTD constraints.
    • The Parameterclass property of the <select> element is changed to the ParameterType property.
    • The Resultclasss property of the <select> element is changed to the Resulttype property.
    • The class property of the <parameterMap> element is changed to the type attribute.
    • The ColumnIndex attribute of the <result> element was removed.
    • The nested parameter was changed from #value # to #{value}.
    • <parameter> and other elements of the Jdbctype attribute value, the original "Oraclecursor" value changed to the current "CURSOR", "number" value changed to "NUMERIC".

Ibatis/mybatis support for stored procedures has always been commendable. The previous definition of a stored procedure by using the <procedure> element is as follows:

Listing 12. How stored procedures are called in IBatis
<procedure id= "getValues" parametermap= "GETVALUESPM" >     {? = Call Pkgexample.getvalues (p_id =?)}  </procedure>

,<proccedure> elements have been removed in MyBatis, defined by <select>, <insert>, and <update>:

Listing 13. How stored procedures are called in MyBatis
<select id= "getValues" parametermap= "GETVALUESPM" statementtype= "callable" >     {? = Call Pkgexample.getvalues (p_id =)}  </select>

As shown above, the statement is identified as a stored procedure rather than a normal SQL statement through the StatementType property.

Back to top of page

Code-level changes

As can be seen from the previous example, the biggest change in MyBatis in encoding is to change the most commonly used API from sqlmapclient to Sqlsessionfactory. In addition, the type processor interface was changed from the original typehandlercallback to Typehandler. Finally, the datasourcefactory was also adjusted to move to the Org.apache.ibatis.datasource package, where the method was also fine-tuned. In short, some of the changes exposed at the code level are minimal and do not cause significant porting costs for developers.

Back to top of page

Summarize

This article mainly describes the problems that may be encountered during the migration from IBatis to MyBatis, most of which have been reflected in the above, and if you want to learn MyBatis from scratch, it is recommended to read the official User Guide document from the beginning.

Original: http://www.ibm.com/developerworks/cn/opensource/os-cn-mybatis/

IBatis 2.x and MyBatis 3.0.x differences (from IBatis to MyBatis)

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.