Phoenix Nirvana: From ibatis to mybatis

Source: Internet
Author: User
Tags finally block

Mybatis simple tutorial

Introduction:This article describes the differences between ibatis 2.x and mybatis 3.0.x, as well as the notes for porting from ibatis to mybatis. By studying this article, you will be able to understand the improvements of mybatis and use it for development. This article is more suitable for developers with ibatis basics.



From ibatis to mybatis, are you ready?

For Java EE developers, ibatis is a familiar persistent layer framework. It is an all-in-one object/relationship ing (O/R Mapping) in Hibernate and JPA) prior to the prevalence of solutions, ibaits was the best choice for the persistence layer framework. Even today, with the emergence of persistent layer frameworks, ibatis still has a place in terms of ease of use, flexibility, and flexibility. Especially for SQL developers, the direct support of ibatis for SQL and stored procedures allows them to gain the advantage of ibatis encapsulation without losing the means of SQL optimization, this is hibernate/JPA
Incomparable. Specifically, the main advantages of using the ibatis framework are as follows:

First, ibatis encapsulates the vast majority of JDBC sample code, so that developers only need to pay attention to the SQL itself and do not need to spend the effort to process such as registering a driver, creating a connection, and make sure that the connection is closed.

Secondly, ibatis is the most easy-to-use and mastered framework with the lowest learning cost among all mainstream persistent layer frameworks. Although other persistent layer frameworks are also known as low thresholds and easy to use, it is very difficult to grasp and use them well when you are actually using them. During my work, I often need to participate in interviews. I have heard many applicants describe that their project chose hibernate for technical selection. Later, I found it difficult to control, you have to rewrite the Code with JDBC or ibatis.

Since its launch on the Apache Software Foundation website, ibatis has received the admiration of thousands of Java developers along with its celebrity siblings (HTTP server, tomcat, struts, Maven, ant, etc. However, in middle June this year, when the version 3.0 was released, a "Apache ibatis has been retired" Statement on the ibatis homepage caused a lot of waves in the community. Six years later, ibatis hosted the code on Google Code. The main reason given in the statement is that, compared with Apache, Google
Code is more conducive to the collaborative work of developers and more suitable for rapid release. At the same time, ibatis is renamed mybatis.

From ibatis to mybatis, it is not just a name change. mybatis provides more powerful functions without losing ease of use. On the contrary, the generic and annotation features of JDK have been simplified in many places. Ibatis is indeed about to retire, because a better successor, after 10 Beta versions, has appeared in front of us.

This article will mainly discuss the changes in mybatis and ibatis, so that readers can smoothly transition from ibatis to mybatis.

Back to Top

Started with a mybatis example

If you have been familiar with some common Java EE frameworks, you should know that these frameworks need to provide a global configuration file to specify the settings and parameter information required for normal program operation. For common persistent layer frameworks (such as Hibernate, JPA, and ibatis), you usually need to configure two types of files: one type is used to specify data sources, transaction attributes, and other parameter configuration information (usually an independent file, which can be called a global configuration file ); the other type is used to specify the ing information between database tables and programs (more than one file may be called a ing file ). Mybatis is no exception. Although some of them can be annotated, these two parts are still essential.

According to ibatis's habits, we usually name the global configuration file sqlmapconfig. XML. The file name is not required. In mybatis, the file is often named configuration. XML (after reading the full text, the reader may find that the "sqlmap" that often appears in ibatis is gradually faded in mybatis, except here, for example, the root element of the ibatis configuration file is <sqlmapconfig>, the element of the specified ing file is <sqlmap>, and sqlmapclient. This change is a positive indication that ibatis is only
SQL ing is the core framework. In mybatis, names in Mapper, session, configuration, and other common ORM frameworks are replaced by the following two types of frameworks: the first is to reduce the learning cost brought about by developers in switching frameworks. Secondly, mybatis fully absorbs the good practices of other ORM frameworks. mybatis is now more than just an SQL ing framework ). The information that can be configured in the global configuration file mainly includes the following aspects:

  • Properties --- used to provide a series of key-value pairs consisting of attribute information, which can be used in the entire configuration file.
  • Settings --- used to set the running mode of mybatis, such as whether to enable delayed loading.
  • Typealiases --- specifies an alias for the Java type. You can replace the fully qualified Java class name with an alias in the XML file.
  • Typehandlers --- when mybatis uses preparedstatement to set a value for a placeholder or retrieves a value from the resultset, a specific type of processor is executed.
  • Objectfactory --- mybatis creates a result object through objectfactory. You can inherit defaultobjectfactory to implement your own objectfactory class.
  • Plugins --- used to configure a series of interceptors to intercept the execution of ing SQL statements. You can implement your own interceptor by implementing the interceptor interface.
  • Environments --- used to configure data source information, including connection pool and transaction attributes.
  • Mappers --- all the SQL ing files used in the program are listed here, and these SQL ing sqls are managed by mybatis.

Most of the elements mentioned above are not required. Generally, mybatis provides default values for elements that are not explicitly set. 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"?> <! -- The global configuration files of ibatis and mybatis use different DTD constraints. When upgrading an application from ibatis to mybatis, you must note that (the DTD constraints of the ing files are also different) --> <! Doctype configuration public "-// mybatis.org//dtd config 3.0 //" http://mybatis.org/dtd/mybatis-3-config.dtd "> <configuration> <! -- Configure information related to the data source --> <environments default = "Demo"> <environment id = "Demo"> <transactionmanager type = "JDBC"/> <datasource type = "pooled"> <property name = "driver" value =... /> <Property name = "url" value =... /> <Property name = "username" value = "root"/> <property name = "password" value = "root"/> </datasource> </environment> </ environments> <! -- List ing files --> <mappers> <mapper resource = "footmark/mybatis/demo/userinfomapper. xml"/> </mappers> </configuration>

With this information, mybatis can establish a connection with the database and apply the given connection pool information and transaction attributes. Mybatis encapsulates these operations and exposes a sqlsessionfactory instance for developers to use. It can be seen from the name that this is a factory class for creating sqlsession. Through the sqlsession instance, developers can directly perform business logic operations without having to repeat JDBC-related sample code. The code for generating 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(); 

The above three lines of code can be seen as a sample code for mybatis to create sqlsession. The first line of code loads the configuration file on the class path. Resources is a tool class provided by mybatis. It is used to simplify the loading of resource files and can access files in various paths, however, the most common method is the class path-based representation in the example. If you have some knowledge about hibernate, you will surely find that mybatis is very similar to hibernate in both style and class names, I have seen many times in domestic and foreign Java communities that mybatis is moving closer to hibernate/JPA. Whether this is true or not, persistence technology is gaining a unified understanding in the community after some vigorous competition and development. This is not necessarily a good thing for developers. mybatis
This is just a step closer to the de facto standard.

After completing the global configuration file and obtaining the sqlsession object through mybatis, you can perform data access operations. For ibatis/mybatis, the operation to be executed is actually the SQL statement configured in the ing file. The configurations are basically the same, as shown below:

Listing 2. configuring SQL statements in the ing 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 significance. In mybatis, namespace comes in handy. It makes the ing file and interface binding very natural. Interface binding will be described in detail later. You can use sqlsession to execute an SQL statement as follows:

Listing 3. Use sqlsession to execute the SQL statements configured in the ing File

 try  {  UserInfo userinfo = (UserInfo) sqlSession.selectOne  ("mybatis.demo.UserInfoMapper.getUser", 2);  System.out.println(userinfo);  } finally  {  sqlSession.close();  } 

Note that the use of sqlsession must follow the above format, that is, disable it in the Finally block. To ensure resource release and prevent memory leakage!

The above is a simple and complete mybatis program. It involves four steps: global configuration file, ing file, building sqlsession object, and performing data access operations. The following sections describe the three parts except the sqlsession object.

Back to Top

Changes to the mybatis global configuration file

The main elements of the mybatis global configuration file are basically the same as ibatis, but the usage and names are adjusted. The meaning of the element is not described. The following describes the main differences between the ibatis and mybatis configuration files.

First, the DTD constraints for the two versions are different, and the DTD file for mybatis is already included in the mybatis-3.0.x.jar package under the release package. This directly affects that the root element of the ibatis configuration file is <sqlmapconfig>, while mybatis uses <configuration>.

Second, the usage of <Settings> has changed. The previous format is:

Listing 4. setting attributes in ibatis

 <settings props1="value1" props2="value2"… /> 

The property to be set is directly in the form of a key-value pair as the property of <Settings>. However, in mybatis, it is slightly complicated but more organized:

Listing 5. setting attributes in mybatis

 <settings>  <setting name="props1" value="value1"/>  <setting name="props2" value="value2"/> …… </settings> 

In addition, you can configure the Transaction Manager and data source as follows:

Listing 6. how to configure the Transaction Manager and data source in ibatis

<Transactionmanager type = "JDBC"> <datasource type = "simple"> <property name = "JDBC. Driver" value = "$ {driver}"/> <! -- Other data source information is omitted --> </datasource> </transactionmanager>

In mybatis, adjust it to the following method:

Listing 7. How to configure the Transaction Manager and data source in mybatis

<Environments default = "Demo"> <environment id = "Demo"> <transactionmanager type = "JDBC"/> <datasource type = "pooled"> <property name = "JDBC. driver "value =" $ {driver} "/> <! -- Other data source information is omitted --> </datasource> </environment> </environments>

<Environments> is used to manage data sources. It is mainly used to simplify switching between multiple data source configurations, such as using different configurations for development and release.

Finally, you can specify the ing file in ibatis as follows:

Listing 8. specifying the ing file in ibatis

 <sqlMap resource=... />  <sqlMap resource=... />  <sqlMap resource=... /> 

In mybatis, adjust to the following method:

Listing 9. specifying the ing file in mybatis

 <mappers>  <mapper resource=... />  <mapper resource=... />  </mappers> 

The main starting point of the above adjustments 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 have discussed the global configuration in XML format. In fact, this is not the only choice. mybatis also provides code-based configuration methods:

Listing 10. Using code in mybatis for configuration

Datasource DS = ...... // Obtain a datasource transactionfactory txfactory = new jdbctransactionfactory (); Environment Env = new environment ("Demo", txfactory, DS); configuration CFG = new configuration (ENV); cfg. addmapper (userinfomapper. class); sqlsessionfactory = new sqlsessionfactorybuilder (). build (CFG );

In combination with the preceding configuration file, it is easy to understand the meaning of this code, so we will not repeat it here. However, it should be noted that the addmapper () method of configuration is used. The parameter of this method is usually an interface, and several methods can be defined in the interface, use annotations on the method to specify the ing SQL statement. A typical Interface Definition and corresponding data access methods are as follows:

Listing 11. Bind The ing SQL statement to the method in the interface

// Ing the SQL binding interface public interface userinfomapper {@ select ("select * From userinfo where userid =#{ userid}") Public userinfo getuserinfo (INT userid );} // bind the interface to the corresponding data access method try {// userinfo = (userinfo) sqlsession. selectone ("mybatis. demo. userinfomapper. selectuser ", 2); userinfomapper = sqlsession. getmapper (userinfomapper. class); userinfo = userinfomapper. getuserinfo (1); system. out. println (userinfo);} finally {sqlsession. close ();}

Back to Top

Changes to the mybatis ing File

Mybatis has many format adjustments for ing files, but most of them are just name changes. Modern ide supports Lenovo functions, you can easily obtain the elements and attributes of the current position. Therefore, this will not cause any inconvenience to developers.

For a ing file, the first is a series of attribute name changes, which are only changes in the name, and the usage and meaning are not changed:

  • Like the global configuration file, the root element is changed from <sqlmap> to <mapper> due to changes in the DTD constraints.
  • <SELECT> change the parameterclass attribute of the element to the parametertype attribute.
  • <SELECT> change the resultclasss attribute of the element to the resulttype attribute.
  • The class attribute of <parametermap> and other elements is changed to the type attribute.
  • <Result> the columnindex attribute of the element is removed.
  • The nested parameter is changed from # value # To # {value }.
  • In the jdbctype attribute values of <parameter> and other elements, the original "oraclecursor" value is changed to the current "cursor", and "Number" value is changed to "numeric ".

Ibatis/mybatis's support for stored procedures has always been commendable. Previously, you used the <procedure> element to define a stored procedure. The example is as follows:

Listing 12. How to call a stored procedure in ibatis

 <procedure id="getValues" parameterMap="getValuesPM">     { ? = call pkgExample.getValues(p_id => ?) }  </procedure> 

In mybatis, the <proccedure> element has been removed and is defined by <SELECT>, <Insert>, and <Update>:

Listing 13. How to call a stored procedure in mybatis

 <select id="getValues" parameterMap="getValuesPM" statementType="CALLABLE">     { ? = call pkgExample.getValues(p_id => ?)}  </select> 

As shown above, the statementtype attribute identifies the statement as a stored procedure rather than a common SQL statement.

Back to Top

Code changes

The preceding example shows that the biggest change of mybatis encoding is to change one of the most commonly used APIs from sqlmapclient to sqlsessionfactory. In addition, the type processor interface is changed from typehandlercallback to typehandler. Finally, the performancefactory is adjusted and moved to the org. Apache. ibatis. datasource package. The methods are also fine-tuned. In short, there are few changes made publicly at the code level, which will not cause a large porting cost to developers.

Back to Top

Summary

This article mainly describes the problems that may be encountered during the migration from ibatis to mybatis. Most of the changes have been reflected in the above. If you want to learn mybatis from the beginning, we recommend that you read the official user guide document from the beginning.

References

Learning

  • For more information, see the mybatis website.

  • Browse the mybatis project sent to Google code. You can download the source code, release package, and documentation.
  • Stay tuned to developerworks
    Technical activities and network broadcasts.

  • Visit developerworks
    The Open Source Area provides rich how-to information, tools, and project updates, as well as the most popular articles and tutorials to help you develop with open source code technology, they are used in combination with IBM products.

Discussion

  • Join the Chinese community on developerworks. The community on developerworks is a professional social networking community that provides community functions such as blogs, bookmarks, wiki, groups, contacts, sharing and collaboration for IT professionals around the world.

  • Join
    IBM software download and technical exchange group to participate in online communication.

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.