In-depth introduction to the Mybatis series (6) --- objectFactory, plugins, mappers introduction and configuration, mybatismappers

Source: Internet
Author: User

In-depth introduction to the Mybatis series (6) --- objectFactory, plugins, mappers introduction and configuration, mybatismappers

The previous article titled Mybatis series (v) --- TypeHandler introduction and configuration (mybatis source code) briefly gave a look at TypeHandler. This will end the study of mybatis configuration files, configuration of several nodes not mentioned in this section: objectFactory, databaseIdProvider, plugins, and mappers.

Next, let's briefly introduce the functions of these configurations:

1. What does objectFactory do? Need to be configured?

Every time MyBatis creates a new instance of the result object, it uses an ObjectFactory instance. The default object factory only needs to instantiate the target class, either by default constructor or by parameter constructor when parameter ing exists. By default, we do not need to configure it. mybatis will call the default objectFactory. Unless we need to customize the implementation of ObjectFactory, We need to manually configure it.

So how to customize the implementation of ObjectFactory? How to configure it?

To customize ObjectFactory, you only need to inherit DefaultObjectFactory (The implementation class of the ObjectFactory Interface) and override its method. I will not talk about it here, but I will explain it later.

After writing ObjectFactory, you only need to make the following Configuration:

<configuration>    ......    <objectFactory type="org.mybatis.example.ExampleObjectFactory">        <property name="someProperty" value="100"/>    </objectFactory>    ......  </configuration

 

2. What is the role of plugin? Need to be configured?

Plugins is an optional configuration. Plugin mybatis is actually an interceptor. It can intercept some methods of Executor, ParameterHandler, ResultSetHandler, and StatementHandler to process our own logic. Executor is what actually executes SQL statements. ParameterHandler is used to process input parameters. As mentioned in TypeHandler, mybatis has implemented many typeHandler by default, when typeHandler configuration is not displayed, mybatis automatically selects the appropriate typeHandler for execution based on the parameter type. In fact, ParameterHandler is selected. ResultSetHandler processes the returned results.

How to customize plugin? How to configure it?

To customize a plug-in, you need to implement the Interceptor interface. I will explain it in detail later. After definition, the configuration is as follows:

<configuration>    ......    <plugins>      <plugin interceptor="org.mybatis.example.ExamplePlugin">        <property name="someProperty" value="100"/>      </plugin>    </plugins>    ......  </configuration>

 

3. mappers, which leads to one of the core of mybatis. What is the role of mappers? Need to be configured?

Under the mappers node, configure our mapper ing file. The so-called mapper ing file is a bridge for mybatis to build ing between data tables and javabean. In our actual development, a mapper file usually corresponds to a dao interface, which can be seen as the implementation of dao. Therefore, mappers must be configured.

So how to configure it?

<Configuration>... <mappers> <! -- Method 1: use resource to specify --> <mapper resource = "com/dy/dao/userDao. xml"/> <! -- The second method is to specify an interface through the class to form a ing relationship between the interface and the corresponding xml file. However, this method must ensure that the interface and the mapper file have the same name (Case Insensitive ), the interface here is UserDao, which means that the mapper file is UserDao. xml <mapper class = "com. dy. dao. userDao "/> --> <! -- The third method is to directly specify the package and automatically scan the package. Similarly, <package name = "com. dy. dao"/> --> <! -- Method 4: Specify the mapper file location through the url <mapper url = "file ://........ "/> --> </mappers> ...... </configuration>

 

This article is only a brief introduction. More advanced usage and implementation principles will be explained in detail in the practical section below.

The source code for parsing these nodes is similar to those mentioned above, so we will not talk about them any more. I will collapse the source code. If you need it, you can open it.

/*** ObjectFactory node parsing */private void objectFactoryElement (XNode context) throws Exception {if (context! = Null) {// read the value of the type attribute. instantiate ObjectFactory and set it to configuration // here. Let's briefly talk about the configuration object, in fact, it mainly stores the configuration String type = context of mybatis. getStringAttribute ("type"); // read the propertie value. You can configure it as needed. The default objectFactory implemented by mybatis does not use properties Properties properties = context. getChildrenAsProperties (); ObjectFactory factory = (ObjectFactory) resolveClass (type ). newInstance (); factory. setProperties (properties); Configuration. setObjectFactory (factory) ;}/ *** plugins node parsing */private void pluginElement (XNode parent) throws Exception {if (parent! = Null) {for (XNode child: parent. getChildren () {String interceptor = child. getStringAttribute ("interceptor"); Properties properties = child. getChildrenAsProperties (); // it can be seen that when defining an interceptor, we need to implement Interceptor. I will explain Interceptor interceptorInstance = (Interceptor) in detail) resolveClass (interceptor ). newInstance (); interceptorInstance. setProperties (properties); configuration. addInterceptor (I NterceptorInstance) ;}}/ *** mappers node parsing * is one of the core of mybatis, in the next article, we will analyze it */private void mapperElement (XNode parent) throws Exception {if (parent! = Null) {for (XNode child: parent. getChildren () {if ("package ". equals (child. getName () {// if the child node of the mappers node is package, scan the files in the package and inject them into configuration String mapperPackage = child. getStringAttribute ("name"); configuration. addMappers (mapperPackage);} else {String resource = child. getStringAttribute ("resource"); String url = child. getStringAttribute ("url"); String mapperClass = child. getString Attribute ("class"); // resource, url, and class. Select if (resource! = Null & url = null & mapperClass = null) {ErrorContext. instance (). resource (resource); InputStream inputStream = Resources. getResourceAsStream (resource); // mapper ing files are parsed through XMLMapperBuilder mapperParser = new XMLMapperBuilder (inputStream, configuration, resource, configuration. getSqlFragments (); mapperParser. parse ();} else if (resource = null & url! = Null & mapperClass = null) {ErrorContext. instance (). resource (url); InputStream inputStream = Resources. getUrlAsStream (url); XMLMapperBuilder mapperParser = new XMLMapperBuilder (inputStream, configuration, url, configuration. getSqlFragments (); mapperParser. parse ();} else if (resource = null & url = null & mapperClass! = Null) {Class <?> MapperInterface = Resources. classForName (mapperClass); configuration. addMapper (mapperInterface);} else {throw new BuilderException ("A mapper element may only specify a url, resource or class, but not more than one. ");}}}}}View Code

 

This is just the end of this Article. Starting from the next article, we will be able to access the core part of mybatis. However, we should first talk about the configuration and usage of the mapper file, and further deepen the core through the source code.

 

 


Can the mybatis configuration file mappers be a local file?

You can configure mybatis mappers in four ways:
1: Use classpath to apply resources
<! -- Using classpath relative resources -->
<Mappers>
<Mapper resource = "org/mybatis/builder/AuthorMapper. xml"/>
<Mapper resource = "org/mybatis/builder/BlogMapper. xml"/>
<Mapper resource = "org/mybatis/builder/PostMapper. xml"/>
</Mappers>
2: Use a local file
<! -- Using url fully qualified paths -->
<Mappers>
<Mapper url = "file: // var/mappers/AuthorMapper. xml"/>
<Mapper url = "file: // var/mappers/BlogMapper. xml"/>
<Mapper url = "file: // var/mappers/PostMapper. xml"/>
</Mappers>
3: Use the Interface Class
<! -- Using mapper interface classes --> <mappers>
<Mapper class = "org. mybatis. builder. AuthorMapper"/>
<Mapper class = "org. mybatis. builder. BlogMapper"/>
<Mapper class = "org. mybatis. builder. PostMapper"/>
</Mappers>
4: Use the package name
<! -- Register all interfaces in a package as mappers -->
<Mappers>
<Package name = "org. mybatis. builder"/>
</Mappers>
Reference: mybatis official guide

After mybatis is configured, MapperScannerConfigurer is injected with the er. Why is an error reported when Tomcat is started? I must write the Impl of dao.

Can you check it?
This error is generally reported. As follows:

<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 // EN"
"Mybatis.org/dtd/mybatis-3-mapper.dtd">
<! -- The namespace must point to the namespace under the Dao interface = which is not defined later -->
<Mapper namespace = "cn.com. casking. log. db. dao. EventMybatisDao">
<SQL id = "limitPrefix">
<! [CDATA [select * from (select row_limit. *, rownum _ from (]>
</SQL>

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.