Home Backend Development XML/RSS Tutorial Detailed example of My Batis XML mapping configuration file

Detailed example of My Batis XML mapping configuration file

Apr 24, 2017 am 09:33 AM

[java] view plain copy

<span style="font-size:14px;">  My Batis 支持SQL查询,是一些高级映射在持久层的完美展示。他更多的使用简单的XML或注解用于配置和原始映射,<span style="color: rgb(54, 54, 54); font-family: &#39;Helvetica Neue&#39;, Helvetica, Arial, sans-serif; line-height: 24px; ">摒除了大量的JDBC代码、手工设置参数和结果集封装,提高了开发效率。</span></span>
Copy after login

The XML configuration file of MyBatis contains settings and attribute information that profoundly affect the behavior of MyBatis. The high-level structure of the XML document is as follows:

configuration configuration

environment environment variable

transactionManager transaction manager

dataSource data source

properties

settings

typeAliases type naming

typeHandlers type processor

objectFactory object factory

plugins

environments

Mapper

The following is a detailed introduction to each property configuration

Properties
These are externalized and replaceable Properties, which can also be configured in a typical Java property configuration file, or passed through child elements of the properties element.

                                                                                                                                                                     

[html] view plain copy
<properties resource="jdbc_mysql.properties" />  
[html] view plain copy
<dataSource type="POOLED">  
[html] view plain copy
<property name="driver" value="${driver}"/>  
[html] view plain copy
<property name="url" value="${url}"/>  
[html] view plain copy
<property name="username" value="${username}"/>  
[html] view plain copy
<property name="password" value="${password}"/>  
[html] view plain copy
</dataSource>
Copy after login

                         The username and password in this example will be replaced by the values ​​set in the properties element. The driver and url properties will be replaced with values ​​from the included jdbc_mysql.properties file.

Settings
These are extremely important adjustments that will modify the way MyBatis behaves at runtime. The following table describes the setting information, their meaning and default values.

Setting parameters                                                                                                    Configure the global mapper to enable or disable caching.

lazyLoadingEnabled Globally enables or disables lazy loading. When disabled, all associated objects are loaded on the fly.

aggressiveLazyLoading When enabled, objects with lazy loading properties will fully load any properties when called. Otherwise, each property will be loaded as needed.

multipleResultSetsEnabled Allows or disallows multiple result sets to be returned from a single statement (appropriate driver required).

useColumnLabel Use column labels instead of column names. Different drivers behave differently here. Refer to the driver documentation or thorough testing to determine which driver to use.

useGeneratedKeys Allows JDBC to support generated keys. A suitable driver is required. If set to true this setting forces the generated keys to be used, although some drivers refuse compatibility but still work (such as Derby).

autoMappingBehavior Specifies how MyBatis automatically maps columns to fields/properties. PARTIAL will only automatically map simple, no nested results. FULL automatically maps arbitrarily complex results (nested or otherwise).

defaultExecutorType Configure the default executor. There is nothing special about the SIMPLE actuator. The REUSE executor reuses prepared statements. BATCH executor reuse statements and batch updates

defaultStatementTimeout Set the timeout, which determines how long the driver waits for a database response.

An example of setting information elements. The complete configuration is as follows:

<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="enhancementEnabled" value="false"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
Copy after login

typeAliases


Type alias is to give a short name to a Java type. It is only relevant for XML configuration and is only used to reduce the redundant part of the fully qualified class name. For example:

[html] view plain copy
<typeAliases>  
[html] view plain copy
<typeAlias alias="Author" type="domain.blog.Author"/>  
[html] view plain copy
<typeAlias alias="Blog" type="domain.blog.Blog"/>  
[html] view plain copy
<typeAlias alias="Comment" type="domain.blog.Comment"/>  
[html] view plain copy
<typeAlias alias="Post" type="domain.blog.Post"/>  
[html] view plain copy
<typeAlias alias="Section" type="domain.blog.Section"/>  
[html] view plain copy
<typeAlias alias="Tag" type="domain.blog.Tag"/>  
[html] view plain copy
</typeAliases>
Copy after login

With this configuration, "Blog" can be used anywhere in place of "domain.blog.Blog".

typeHandlers

Whether MyBatis sets a parameter in a prepared statement or retrieves a value from the result set, the type handler is used to convert the obtained value into a Java type in an appropriate manner. The following list describes the default type handlers. In order, type handler Java type JDBC type


BooleanTypeHandler Boolean, boolean Any compatible Boolean value

ByteTypeHandler Byte, byte Any compatible number or byte type

ShortTypeHandler Short , short Any compatible number or short type ##

FloatTypeHandler Float,float 任何兼容的数字或单精度浮点型

DoubleTypeHandler Double,double 任何兼容的数字或双精度浮点型

BigDecimalTypeHandler BigDecimal 任何兼容的数字或十进制小数类型

StringTypeHandler String CHAR和VARCHAR类型

ClobTypeHandler String CLOB和LONGVARCHAR类型

NStringTypeHandler String NVARCHAR和NCHAR类型

NClobTypeHandler String NCLOB类型

ByteArrayTypeHandler byte[] 任何兼容的字节流类型

BlobTypeHandler byte[] BLOB和LONGVARBINARY类型

DateTypeHandler Date(java.util) TIMESTAMP类型

DateOnlyTypeHandler Date(java.util) DATE类型

TimeOnlyTypeHandler Date(java.util) TIME类型

SqlTimestampTypeHandler Timestamp(java.sql) TIMESTAMP类型

SqlDateTypeHandler Date(java.sql) DATE类型

SqlTimeTypeHandler Time(java.sql) TIME类型

ObjectTypeHandler Any 其他或未指定类型

EnumTypeHandler Enumeration类型 VARCHAR-任何兼容的字符串类型,作为代码存储(而不是索引)。

objectFactory
MyBatis每次创建结果对象新的实例时,它使用一个ObjectFactory实例来完成。如果参数映射存在,默认的ObjectFactory不比使用默认构造方法或带参数的构造方法实例化目标类做的工作多。

plugins
MyBatis允许你在某一点拦截已映射语句执行的调用。默认情况下,MyBatis允许使用插件来拦截方法调用:

Executor
            (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
 ParameterHandler
            (getParameterObject, setParameters)
 ResultSetHandler
          (handleResultSets, handleOutputParameters)
 StatementHandler
Copy after login

(prepare, parameterize, batch, update, query)
这些类中方法的详情可以通过查看每个方法的签名来发现,而且它们的源代码在MyBatis的发行包中有。你应该理解你覆盖方法的行为,假设你所做的要比监视调用要多。如果你尝试修改或覆盖一个给定的方法,你可能会打破MyBatis的核心。这是低层次的类和方法,要谨慎使用插件。

使用插件是它们提供的非常简单的力量。简单实现拦截器接口,要确定你想拦截的指定签名。

java代码:

[javascript] view plain copy
@Intercepts({@Signature(type= Executor.class,method = "update",  
[javascript] view plain copy
args = {MappedStatement.class,Object.class})})  
[javascript] view plain copy
public class ExamplePlugin implements Interceptor {  
[javascript] view plain copy
public Object intercept(Invocation invocation) throws Throwable  
[javascript] view plain copy
{  
[javascript] view plain copy
return invocation.proceed();  
[javascript] view plain copy
}  
[javascript] view plain copy
public Object plugin(Object target) {  
[javascript] view plain copy
return Plugin.wrap(target, this);  
[javascript] view plain copy
}  
[javascript] view plain copy
public void setProperties(Properties properties) {  
[javascript] view plain copy
}  
[html] view plain copy
MapperConfig.xml  
[html] view plain copy
<plugins>  
[html] view plain copy
<plugin interceptor="org.mybatis.example.ExamplePlugin">  
[html] view plain copy
<property name="someProperty" value="100"/>  
[html] view plain copy
</plugin>  
[html] view plain copy
</plugins>  
[html] view plain copy
Copy after login

上面的插件将会拦截在Executor实例中所有的“update”方法调用,它也是负责低层次映射语句执行的内部对象。

environments

[html] view plain copy
<environments default="development">  
        <environment id="development">  
            <transactionManager type="JDBC" />  
            <dataSource type="POOLED">  
                <property name="driver" value="${jdbc.driver}" />  
                <property name="url" value="${jdbc.url}"/>  
                <property name="username" value="${jdbc.user}" />  
                <property name="password" value="${jdbc.password}" />  
                                <property name="poolPingEnabled" value="true"/>  
                <property name="poolPingQuery" value="SELECT * FROM app_setup_setting WHERE name=&#39;allow_setup_unknown_app&#39;" />  
                        <property name="poolPingConnectionsNotUsedFor" value="7200000"/>   
            </dataSource>  
        </environment>  
    </environments>  
dataSsource
Copy after login

dataSource元素使用基本的JDBC数据源接口来配置JDBC连接对象的资源。见上
transactionManager

在MyBatis中有两种事务管理器类型(也就是type=”[JDBC|MANAGED]”):
1.JDBC – 这个配置直接简单使用了JDBC的提交和回滚设置。它依赖于从数据源得到的连接来管理事务范围。
2.MANAGED – 这个配置几乎没做什么。它从来不提交或回滚一个连接。而它会让容器来管理事务的整个生命周期(比如Spring或JEE应用服务器的上下文)。默认情况下它会关闭连接。然而一些容器并不希望这样,因此如果你需要从连接中停止它,将closeConnection属性设置为false。例如:

[html] view plain copy
<transactionManager type="MANAGED">  
<property name="closeConnection" value="false"/>  
</transactionManager>
Copy after login

这两种事务管理器都不需要任何属性。然而它们都是类型别名,要替换使用它们,你需要放置将你自己的类的完全限定名或类型别名,它们引用了你对TransacFactory接口的实现类。
public interface TransactionFactory {
void setProperties(Properties props);
Transaction newTransaction(Connection conn, boolean autoCommit);
}
任何在XML中配置的属性在实例化之后将会被传递给setProperties()方法。你的实现类需要创建一个事务接口的实现,这个接口也很简单:

[html] view plain copy
public interface Transaction {  
Connection getConnection();  
void commit() throws SQLException;  
void rollback() throws SQLException;  
void close() throws SQLException;  
}
Copy after login

使用这两个接口,你可以完全自定义MyBatis对事务的处理。

mappers

既然MyBatis的行为已经由上述元素配置完了,我们现在就要定义SQL映射语句了。但是,首先我们需要告诉MyBatis到哪里去找到这些语句。Java在这方面没有提供一个很好的方法,所以最佳的方式是告诉MyBatis到哪里去找映射文件。你可以使用相对于类路径的资源引用,或者字符表示,或url引用的完全限定名(包括file:///URLs)。例如:

[html] view plain copy
// 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>  
// Using url fully qualified paths  
<mappers>  
<mapper url="file:///var/sqlmaps/AuthorMapper.xml"/>  
<mapper url="file:///var/sqlmaps/BlogMapper.xml"/>  
<mapper url="file:///var/sqlmaps/PostMapper.xml"/>  
</mappers>
Copy after login

The above is the detailed content of Detailed example of My Batis XML mapping configuration file. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Filtering and sorting XML data using Python Filtering and sorting XML data using Python Aug 07, 2023 pm 04:17 PM

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Using Python to merge and deduplicate XML data Using Python to merge and deduplicate XML data Aug 07, 2023 am 11:33 AM

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Python implements conversion between XML and JSON Python implements conversion between XML and JSON Aug 07, 2023 pm 07:10 PM

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling errors and exceptions in XML using Python Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Import XML data into database using PHP Import XML data into database using PHP Aug 07, 2023 am 09:58 AM

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Use PHP and XML to process and display geolocation and map data Use PHP and XML to process and display geolocation and map data Aug 01, 2023 am 08:37 AM

Processing and displaying geolocation and map data using PHP and XML Overview: Processing and displaying geolocation and map data is a common requirement when developing web applications. PHP is a popular server-side programming language that can interact with data in XML format. This article explains how to use PHP and XML to process and display geolocation and map data, and provides some sample code. 1. Preparation: Before starting, you need to ensure that PHP and related extensions, such as Simple, are installed on the server

See all articles