Detailed example of My Batis XML mapping configuration file

Y2J
Release: 2017-04-24 09:33:29
Original
2115 people have browsed it

[java] view plain copy

  My Batis 支持SQL查询,是一些高级映射在持久层的完美展示。他更多的使用简单的XML或注解用于配置和原始映射,摒除了大量的JDBC代码、手工设置参数和结果集封装,提高了开发效率。
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
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
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:










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
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
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
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
  
[html] view plain copy
Copy after login

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

environments

[html] view plain copy
  
          
              
              
                  
                  
                  
                  
                                  
                  
                           
              
          
      
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
  
  
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(首选)  
  
  
  
  
  
// Using url fully qualified paths  
  
  
  
  
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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!