MyBatis User's Guide

sponsored links
MyBatis 3
User's Guide to help us to better document ...
If you find omissions in this document, a description or missing MyBatis characteristics, then the best way to find out the omissions and then put it down.
We receive public documents in the wiki contributions:
http://code.google.com/p/mybatis/wiki/Welcome
You are the best of this document, other users will be to read it.
About Translation
MyBatis 3 user guide translation done by the South Lei, if you have any comments on the quality of translation and suggestions, please contact nanlei1987@gmail.com, and everyone is willing to jointly improve and common progress.
Copy the code from the document warning right, this is not a legal warning, but it can help you maintain a clear understanding. Aesthetically speaking, the modern word processing tools in the production of readable text and formatting done a lot of good work. However, they also tend to insert special characters and the complete destruction of code samples, sometimes you seem to want is exactly the same. "Quotes" and the hyphen is a good example - the environment in the IDE or text editor, left the symbols do not normally work, at least not the effect you want.
Reading this document, we should enjoy it, hope it will help you. When confronted with code examples, they can look for examples and download (including unit testing, etc.), or from the Web site and mailing list of examples.
Contents What is MyBatis? .................................................. .................................................. ......... 5
Introduction ................................................. .................................................. ............................. 5
From the XML build SqlSessionFactory ............................................. ................................. 5
Do not use XML build SqlSessionFactory ............................................. .............................. 6
To obtain from the SqlSessionFactory SqlSession ............................................. .......................... 6
Explore the SQL statement has been mapped ............................................ ................................................ 7
Namespace A note ............................................. ............................................. 8
Range and life cycle .............................................. .................................................. ........ 8
SqlSessionFactoryBuilder ................................................. .................................... 8
SqlSessionFactory ................................................. ............................................... 9
SqlSession ................................................. .................................................. 9 .......
Mapper instances ................................................ .................................................. ..... 9
XML mapping configuration file .............................................. .................................................. ........ 10
properties ................................................. .................................................. .............. 10
Settings ................................................. .................................................. ................. 11
typeAliases ................................................. .................................................. ........... 12
typeHandlers ................................................. .................................................. ......... 13
objectFactory ................................................. .................................................. ........ 14
plugins ................................................. .................................................. ................. 15
environments ................................................. .................................................. ......... 16
transactionManager ................................................. ........................................... 17
dataSsource ................................................. .................................................. .... 17
mappers ................................................. .................................................. ................ 19
SQL Map XML files ............................................. .................................................. .... 19
select ................................................. .................................................. .................... 20
insert, update, delete ............................................. ................................................. 21
sql ................................................. .................................................. ........................ 23
Parameters ................................................. .................................................. ............ 24
resultMap ................................................. .................................................. ............. 25
Senior Results Mapping ............................................... .................................................. .. 27
id, result ............................................... .................................................. ......... 29
Supported JDBC Type .............................................. .............................................. 30
Constructor ................................................ .................................................. ........ 30
Related ................................................. .................................................. .............. 31
Collection ................................................. .................................................. .............. 34
Discriminator ................................................ .................................................. ........... 36
Caching ................................................. .................................................. ..................... 38
Using a custom cache .............................................. ................................................. 38
Reference to the cache ................................................ .................................................. ............... 39
Dynamic SQL ................................................ .................................................. .............. 39
if ................................................. .................................................. .................. 40
choose, when, otherwise ............................................. ........................................ 40
trim, where, set ............................................. .................................................. ... 41
foreach ................................................. .................................................. .......... 43
Java API ................................................ .................................................. ....................... 43
Application Directory Structure ............................................... .................................................. ......... 43
SqlSessions ................................................. .................................................. ........... 44
SqlSessionFactoryBuilder ................................................. .................................. 44
SqlSessionFactory ................................................. ............................................. 46
SqlSession ................................................. .................................................. ..... 47
SelectBuilder ................................................. .................................................. .. 53
SqlBuilder ................................................. .................................................. ..... 56
What is MyBatis?
MyBatis support the general SQL queries, stored procedures and advanced mapping persistence framework for good. MyBatis eliminate almost all manual JDBC code and parameter settings, and result set retrieval. MyBatis using simple XML or annotations for configuration and the original mapping, the interface and Java for POJOs (Plan Old Java Objects, ordinary Java objects) map to records in the database.
Entry for each application that MyBatis SqlSessionFactory instance of an object with a core. SqlSessionFactory instance of an object can be obtained by SqlSessionFactoryBuilder object. SqlSessionFactoryBuilder object from the XML configuration file, or from the Configuration class instance of the habit of preparing to build SqlSessionFactory object.
From the XML build SqlSessionFactory
From the XML file is very simple examples of building SqlSessionFactory. It is recommended that you use the class path of the resource file to configure, but you can use any of the Reader instance, the examples include the form of the text file path file path or URL in the form file: / / to create. MyBatis contains a number of tools, known as resources, these tools contain a number of methods that make the path from a class or other resource files to load much easier.
String resource = "org / mybatis / example / Configuration.xml";
Reader reader = Resources.getResourceAsReader (resource);
sqlMapper = new SqlSessionFactoryBuilder (). build (reader);
XML configuration file contains the core set of MyBatis system, including database connection instance for the data sources and determine the scope and control of transaction transaction manager. XML configuration files on the details later in the document can be found here give a simple example:
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE configuration PUBLIC "- / / mybatis.org / / DTD Config 3.0 / / EN"
"Http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment>
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</ DataSource>
</ Environment>
</ Environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</ Mappers>
</ Configuration>
Of course, there are many XML configuration file can be configured, the above example to point out is the most critical part. XML declaration should pay attention to the head, you need to verify the correctness of XML documents. element contains the body of environment affairs and environment connection pool configuration. element contains all the mappers mapper (mapper) list, the mapper's XML file contains the SQL code and mapping information.
Do not use XML build SqlSessionFactory
If you like, not from the Java program directly to create a configuration XML file instance, or create your own configuration builder, MyBatis also provides a complete configuration class, provide all the load from the XML file configuration options.
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource ();
TransactionFactory transactionFactory = new
JdbcTransactionFactory ();
Environment environment =
new Environment ("development", transactionFactory, dataSource);
Configuration configuration = new Configuration (environment);
configuration.addMapper (BlogMapper.class);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder (). build (configuration);
Note that this case is to add mapping class configuration. Mapping class is Java classes that contain SQL statements annotations mapping XML documents so as to avoid dependence, XML mapping is still in the majority of advanced mapping (eg: Join nested mapping) is required. For this reason, if the XML configuration file exists, then, MyBatis will automatically find and load an XML file, etc. (in this case, based on the class path of the BlogMapper.class class class name, then BlogMapper.xml will be loaded.) Later we will understand more.
Get SqlSession from SqlSessionFactory
Now, we already know how to get SqlSessionFactory objects, based on the same revelation, we can get SqlSession the instance. SqlSession object is fully contained in the database as the background for all methods perform SQL operations. You can use SqlSession instance mapped directly executed SQL statement. For example:
SqlSession session = sqlMapper.openSession ();
try {
Blog blog = (Blog) session.selectOne (
"Org.mybatis.example.BlogMapper.selectBlog", 101);
} Finally {
session.close ();
}
The role of this approach, and we use the previous MyBatis version is similar, there is a more concise way. Describe the parameters and the use of reasonable value of the SQL statement returns the interface (for example BlogMapper.class), so now you can point that a simpler, more secure code, not a string of text and prone to conversion errors.
For example:
SqlSession session = sqlSessionFactory.openSession ();
try {
BlogMapper mapper = session.getMapper (BlogMapper.class);
Blog blog = mapper.selectBlog (101);
} Finally {
session.close ();
}
Now look here, in the end we come to explore what performed.
SQL statement has been mapped to explore where you might want to know and Mapper objects in the end by SqlSession what actions performed. Mapped SQL statement is a big theme, and this theme will run through most of the contents of this document. In order to give a macro concept, here are some examples.
Any of the above-mentioned example, the statement is defined by XML or annotations. Let's take a look at XML. Mapping using the XML-based language, in the past few years makes MyBatis very popular with all his MyBatis feature set. If you've used MyBatis, should be very familiar with this concept, but the XML mapping file, there are many improvements, we will detail it later. Here is an example based on XML mapping statements, these statements should meet the above example SqlSession object calls.
<? 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="org.mybatis.example.BlogMapper">
<select parameterType="int" resultType="Blog">
select * from Blog where id = # {id}
</ Select>
</ Mapper>
This simple example seems to have a lot of extra stuff, but it is simple and the. You can map a single XML file defines the mapping of many statements, in addition to XML and document type declaration outside of the head, you can get at a lot of convenience. The remainder of the document is a good self-explanation. In the namespace "com.mybatis.example.BlogMapper", it defines a named "selectBlog" mapping statement, so it allows you to use the fully qualified name "org.mybatis.example.BlogMapper.selectBlog" statement to call the map , we have written all of the following example is the case.
Blog blog = (Blog) session.selectOne (
"Org.mybatis.example.BlogMapper.selectBlog", 101);
Note that using the fully qualified name of the method call Java objects are similar, there is a reason to do so. This name can be directly to the same namespace mapping class, the use of a name, parameters and return values and the query are mapped the same way as you can. This allows you to easily call the methods in the mapping interface, which you saw earlier is the same, the following example, it has emerged.
BlogMapper mapper = session.getMapper (BlogMapper.class);
Blog blog = mapper.selectBlog (101);
There are many ways the second bit, first of all it is not text-based, it would be more secure. Second, if your IDE has code completion feature, you can use it to manipulate the SQL statement has been mapped. Third, do not need a cast, while BlogMapper interface can keep it simple, safe return type (parameter type is also very safe.)
Note that the namespace mapping, such as BlogMapper this class, there are still a coup. Among them mapped statement can not be written in XML, but you can use Java annotations to replace. For example, the XML example above can be replaced as follows:
package org.mybatis.example;
public interface BlogMapper {
@ Select ("SELECT * FROM blog WHERE id = # {id}")
Blog selectBlog (int id);
}
For simple statements, the use of annotated code will be more clear, however, Java annotations for complex statements, it will be chaos, should be limited. So if you have to do complex things, it is best to use XML to map statement.
Of course, this also depends on you and your project team decided to see which is more suitable for you to use, as well as the long-term approach to the importance of using a mapped statement. In other words, do not limit yourself in a way. You can easily replace the XML mapping annotations statement, and vice versa.
Understanding of the scope and life cycle have already discussed our current range and life cycle of the different classes is very important. Do not use them correctly can lead to serious concurrency issues.
SqlSessionFactoryBuilder
This class can be instantiated, used and discarded. Once you have created SqlSessionFactory after this class do not need to exist. Therefore, the best range SqlSessionFactoryBuilder instance method scope (that is, a local method variable.) You can reuse the SqlSessionFactoryBuilder to create multiple SqlSessionFactory instance, but not the best way to keep it there has been to ensure that all XML parsing resources, because there are more important things to do.
Namespace in the previous version of the MyBatis is optional, is very confusing and no help. Now, the namespace is a must, and have a purpose, it uses the fully qualified name longer to isolate the statement.
Namespace makes it possible to bind the interface, as you see, do not know if before, now you'll use them, you should follow the example given below to practice, so as not to change his mind. Use namespaces and Java packages it in the appropriate space below to make your code will become simple, in a very long time to improve MyBatis role.
Name resolution: To reduce the input, MyBatis configuration elements for all the naming resolution using the following naming rules, including statements, the results of mapping, and caching.
 directly to find the fully qualified name (such as "com.mypackage.MyMapper.selectAllThings"), if found to use.
 short name (such as "selectAllThings") can be used to refer to any vague object. If two or more (such as "com.foo.selectAllThings" and "com.bar.selectAllThings"), you will get an error report or a short name is ambiguous, and therefore must use the fully qualified name .
SqlSessionFactory
Once created, SqlSessionFactory your application should exist during the execution. There is no reason to deal with or re-create it. The best practice is to use SqlSessionFactory application created during the operation not to repeat several times. This operation will be regarded as very bad. Therefore, the best range SqlSessionFactory applications. There are many ways to do the simplest is to use a singleton pattern or a static singleton. However, these two methods are not considered best practice. In this case, you might consider dependency injection container, such as Google Guice or Spring. This framework allows you to create support programs to manage the life cycle of a single case SqlSessionFactory.
SqlSession
Each thread should have its own SqlSession instance. SqlSession instance can not be shared, but also thread safe. So the best method of range or scope of the request. Must not be SqlSession reference to an instance in a static field or even the class instance field. SqlSession can never put any type of reference to an instance of the scope of management, such as Serlvet architecture HttpSession. If you are using any Web framework and to consider SqlSession HTTP request object in a similar range. In other words, based on the received HTTP request, you can open a SqlSession, and then returns a response, you can close it. Close Session is very important, you should be sure to use the finally block to close it. The following example is a basic model to ensure SqlSession off:
SqlSession session = sqlSessionFactory.openSession ();
try {
/ / Do work
} Finally {
session.close ();
}
Consistent in your code to use this mode, the database will ensure that all resources are properly closed (assuming you do not pass your own connection is closed, it will MyBatis signs that you create a connection to manage resources).
Mapper Mapper instance is that you create a binding interface mapping statement. Instance mapping interface can be obtained from the SqlSession. So technically, when requested, any instance mapping and SqlSession widest range are the same. However, the best range of mapping instance the method scope. That is, they should use their method is requested, and then discarded. They do not need to explicitly turn off, then keep them in the request object will not be a problem, and this and SqlSession similar. You may find, at this level if too many resources management will be out of control. Keep it simple, the mapper on the method of range. The following example to demonstrate this practice:
SqlSession session = sqlSessionFactory.openSession ();
try {
BlogMapper mapper = session.getMapper (BlogMapper.class);
/ / Do work
} Finally {
session.close ();
}
XML mapping configuration file
MyBatis the XML configuration file contains settings profound impact MyBatis behavior and attribute information. High-level XML document is structured as follows:
 configuration attributes  settings configuration  properties set  typeAliases type named type of processor  objectFactory  typeHandlers object factory  plugins plug  environments  environment environment environment variable  transactionManager transaction manager   dataSource data source mapper
properties
These are external-oriented, alternative properties that can be configured in a typical Java properties configuration file, or by child elements properties to pass. For example:
<properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</ Properties>
Attribute which can be used in the configuration file, use the properties to replace the dynamic configuration. For example:
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</ DataSource>
This example, the username and password will be set by the value of properties element to replace. driver and url properties will come from the config.properties file that contains the value to replace. Here are many configuration options.
Properties may be passed to SqlSessionBuilder.build () method. For example:
SqlSessionFactory factory =
sqlSessionFactoryBuilder.build (reader, props);
/ / ... Or ...
SqlSessionFactory factory =
sqlSessionFactoryBuilder.build (reader, environment, props);
If in these areas, more than one property, then, MyBatis load them in the following order:
 specified in the properties element in vivo properties of the first to be read.
 resources from the classpath or properties under the url attribute of the element properties of the second load is read, it will overwrite the existing exactly the same properties.
 properties as a method parameter is read last, it will cover any of the existing exactly the same properties, which may be elements of the body from the properties and resources / url attributes loaded.
Therefore, the properties of the highest priority are those that as a method parameter, then the resource / url attribute and, finally, the attributes specified in the properties element.
Settings
These are extremely important to adjust, they will modify the MyBatis in the run-time behavior. The following table describes the settings, their meanings and default values. RMS default values set the parameters described
cacheEnabled
The global mapper configured to enable or disable caching.
true | false
true
lazyLoadingEnabled
Globally enable or disable delayed loading. When disabled, all associated objects are immediately loaded.
true | false
true
aggressiveLazyLoading
When enabled, a delay in loading the object attributes will be called when any attribute is fully loaded. Otherwise, each property will be loaded as needed.
true | false
true
multipleResultSetsEnabled
Allow or not allow multiple result sets from a single statement to return (with appropriate drivers).
true | false
true
useColumnLabel
Use the column labels instead of column names. Different drivers behave differently in this convenient. Refer to the full test drive documentation or the use of two methods to determine the driver.
true | false
true
useGeneratedKeys
JDBC support allows the generated keys. Need for the driver. If set to true then this setting forces generated keys are used, although some drivers refused to compatible but still effective (such as Derby).
true | false
false
autoMappingBehavior
How to automatically map out the specified MyBatis to the field / property. PARTIAL will automatically map a simple, no nested results. FULL will automatically map the results of any complex (nested or otherwise).
NONE,
PARTIAL,
FULL
PARTIAL
defaultExecutorType
Configure the default actuators. SIMPLE actuator nothing special. REUSE actuator reuse prepared statement. BATCH actuator reuse statements and batch updates
SIMPLE,
REUSE,
BATCH
SIMPLE
defaultStatementTimeout
Sets the timeout time, it decided to wait for a database-driven response time.
Any positive integer
Not Set
(Null)
Example of a set of information elements, 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>
typeAliases
Type the alias name for the Java type a short name. XML configuration only, and is related only to the fully qualified class name used to reduce the excess. For example:
<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
<typeAlias alias="Blog" type="domain.blog.Blog"/>
<typeAlias alias="Comment" type="domain.blog.Comment"/>
<typeAlias alias="Post" type="domain.blog.Post"/>
<typeAlias alias="Section" type="domain.blog.Section"/>
<typeAlias alias="Tag" type="domain.blog.Tag"/>
</ TypeAliases>
Using this configuration, "Blog" can be used to replace any "domain.blog.Blog" are used where.
For normal Java types, there are many built-in type alias. They are not case-sensitive, due to overloading of the name, pay attention to the native type of special treatment. The type alias mapping
_byte
byte
_long
long
_short
short
_int
int
_integer
int
_double
double
_float
float
_boolean
boolean
string
String
byte
Byte
long
Long
short
Short
int
Integer
integer
Integer
double
Double
float
Float
boolean
Boolean
date
Date
decimal
BigDecimal
bigdecimal
BigDecimal
object
Object
map
Map
hashmap
HashMap
list
List
arraylist
ArrayList
collection
Collection
iterator
Iterator
typeHandlers
In prepared statements, whether MyBatis set a parameter, or remove a value from the result set, the type of processor is used to obtain the value of a suitable way to convert Java types. The following table describes the default type of processor. JDBC Java type type type of processor
BooleanTypeHandler
Boolean, boolean
Boolean value of any compatible
ByteTypeHandler
Byte, byte
Any compatible digital or byte type
ShortTypeHandler
Short, short
Any compatible digital or short integer
IntegerTypeHandler
Integer, int
Any compatible digital and integer
LongTypeHandler
Long, long
Any compatible digital or long integer
FloatTypeHandler
Float, float
Any compatible single-precision floating point numbers or
DoubleTypeHandler
Double, double
Any compatible digital or double precision floating point
BigDecimalTypeHandler
BigDecimal
Any compatible digital or decimal types
StringTypeHandler
String
CHAR and VARCHAR Types
ClobTypeHandler
String
CLOB and LONGVARCHAR type
NStringTypeHandler
String
NVARCHAR and NCHAR type
NClobTypeHandler
String
NCLOB type
ByteArrayTypeHandler
byte []
Byte stream any type of compatible
BlobTypeHandler
byte []
Type BLOB and LONGVARBINARY
DateTypeHandler
Date (java.util)
TIMESTAMP Types
DateOnlyTypeHandler
Date (java.util)
DATE type
TimeOnlyTypeHandler
Date (java.util)
TIME Type
SqlTimestampTypeHandler
Timestamp (java.sql)
TIMESTAMP Types
SqlDateTypeHandler
Date (java.sql)
DATE type
SqlTimeTypeHandler
Time (java.sql)
TIME Type
ObjectTypeHandler
Any
Other or not specified types
EnumTypeHandler
Enumeration Types
VARCHAR-any compatible string type, as code storage (not index).
You can override the type of processor or create your own to deal with the type of processor does not support or non-standard type. Do so, a simple implementation of TypeHandler Interface (org.mybatis.type), and then mapping a new type of processor classes to Java types, as well as optional a JDBC type. For example:
/ / ExampleTypeHandler.java
public class ExampleTypeHandler implements TypeHandler {
public void setParameter (PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
ps.setString (i, (String) parameter);
}
public Object getResult (ResultSet rs, String columnName)
throws SQLException {
return rs.getString (columnName);
}
public Object getResult (CallableStatement cs, int columnIndex)
throws SQLException {
return cs.getString (columnIndex);
}
}
/ / MapperConfig.xml
<typeHandlers>
<TypeHandler javaType = "String" jdbcType = "VARCHAR"
handler = "org.mybatis.example.ExampleTypeHandler" />
</ TypeHandlers>
Using this type of processor will overwrite the existing deal with Java's String type attributes and VARCHAR parameters and result type processor. Note MyBatis not examine the meta-information database to determine which type to use, so you must specify the parameters and the resulting map of type VARCHAR field that is to bind to the correct type of processor. This is because the MyBatis not know until the statement is executed, the data type of this reality caused.
objectFactory
MyBatis each time you create a new instance of the result object, it uses an ObjectFactory instance to complete. If the parameter mapping exists, the default ObjectFactory better than using the default constructor or a constructor with parameters to instantiate the target class to do more work. If you want to override the default ObjectFactory, you can create your own. For example:
/ / ExampleObjectFactory.java
public class ExampleObjectFactory extends DefaultObjectFactory {
public Object create (Class type) {
return super.create (type);
}
public Object create (Class type, List <Class> constructorArgTypes,
List <Object> constructorArgs) {
return super.create (type, constructorArgTypes, constructorArgs);
}
public void setProperties (Properties properties) {
super.setProperties (properties);
}
}
/ / MapperConfig.xml
<objectFactory type="org.mybatis.example.ExampleObjectFactory">
<property name="someProperty" value="100"/>
</ ObjectFactory>
ObjectFactory interface is simple. It contains two methods used to create one is dealing with the default constructor, and the other is to deal with parameter constructor. Finally, setProperties method can be used to configure the ObjectFactory. In the initialize your ObjectFactory instance, objectFactory element attributes defined in the body will be passed to the setProperties method.
plugins
MyBatis allows you to block has been mapped in a statement that the implementation of the call. By default, MyBatis allows the use of plug-in to intercept method calls:
 Executor
(Update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
 ParameterHandler
(GetParameterObject, setParameters)
 ResultSetHandler
(HandleResultSets, handleOutputParameters)
 StatementHandler
(Prepare, parameterize, batch, update, query)
Details of the methodology of these classes can look to find the signature of each method, and their source code distribution package in MyBatis there. You should understand your coverage to the behavior, assuming you do more than monitor the calls to. If you try to modify or overwrite a given method, you may break the MyBatis core. This is a low-level classes and methods, to be careful to use plug-in.
Use plug-ins is that they provide a very simple power. Simple implementation interceptor interface, make sure you want to ban the specified signature.
/ / ExamplePlugin.java
@ Intercepts ({@ Signature (type = Executor.class, method = "update",
args = {MappedStatement.class, Object.class})})
public class ExamplePlugin implements Interceptor {
public Object intercept (Invocation invocation) throws Throwable
{
return invocation.proceed ();
}
public Object plugin (Object target) {
return Plugin.wrap (target, this);
}
public void setProperties (Properties properties) {
}
}
/ / MapperConfig.xml
<plugins>
<plugin interceptor="org.mybatis.example.ExamplePlugin">
<property name="someProperty" value="100"/>
</ Plugin>
</ Plugins>
The above plug-in will intercept all of the Executor instance of "update" method call, it is also responsible for the implementation of low-level internal object mapping statement.
environments
MyBatis can configure a variety of environments. This map will help you to apply a variety of SQL database. For example, you may want to set for the development of different configurations, testing and production environment. Or you may have multiple production databases are sharing the same pattern, so you may want to use the same database for different SQL mapping. The use cases are many.
A very important issue to remember: you can configure a variety of environments, but you can only select one instance for each SqlSessionFactory.
So, if you want to connect two databases, you need to create two SqlSessionFactory instances, each corresponding to a database. If the three databases, you need three examples, and so on. Memory is simple:
 Each database corresponds to a SqlSessionFactory
In order to clarify what kind of environment created, you can use it as an optional parameter to SqlSessionFactoryBuilder. Acceptable environment configuration of the two method signatures are:
SqlSessionFactory factory = sqlSessionFactoryBuilder.build (reader, environment);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build (reader, environment, properties);
If the environment is ignored, then the default environment will be loaded, proceed as follows:
SqlSessionFactory factory = sqlSessionFactoryBuilder.build (reader);
SqlSessionFactory factory = sqlSessionFactoryBuilder.build (reader, properties);
Environment element defines how to configure the environment.
<environments default="development">
<environment>
<transactionManager type="JDBC">
<property name="..." value="..."/>
</ TransactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</ DataSource>
</ Environment>
</ Environments>
Note that the key here:
 default environment ID (eg: default = "development").
 each environment element defines the environment ID (eg: id = "development").
Cover the configuration class in addition to the core with plug-ins to modify the behavior of MyBatis addition, you can completely cover the configuration class. Simple extension of it, and then cover them any way, then pass it to sqlSessionFactoryBuilder.build (myConfig) method call. This may seriously affect the MyBatis behavior, so be careful.
 transaction manager configuration (for example: type = "JDBC").
 data source configuration (eg: type = "POOLED").
The default environment and environmental ID is self-explanatory. You can use the name you like to name, just make sure to match the default one.
transactionManager
There are two in MyBatis transaction manager type (ie type = "[JDBC | MANAGED]"):
 JDBC - This configuration is simple to use direct JDBC, commit and rollback of the set. It depends on the connection from data sources to manage the transaction scope.
 MANAGED - almost did not do this configuration. It never commit or rollback a connection. And it will make the container to manage the affairs of the entire life cycle (such as Spring or JEE application server context.) By default it will close the connection. However, some containers do not want this, so if you need to stop it from the connection will closeConnection property to false. For example:
<transactionManager type="MANAGED">
<property name="closeConnection" value="false"/>
</ TransactionManager>
Both the transaction manager does not need any attributes. However, they are all types of aliases, use them to replace, you need to put your own class or type the fully qualified name of an alias, they refer you to the TransacFactory interface implementation class.
public interface TransactionFactory {
void setProperties (Properties props);
Transaction newTransaction (Connection conn, boolean autoCommit);
}
Any configuration attributes in the XML, after the instantiation will be passed to the setProperties () method. Your class will need to create a transaction to achieve implementation of the interface, this interface is very simple:
public interface Transaction {
Connection getConnection ();
void commit () throws SQLException;
void rollback () throws SQLException;
void close () throws SQLException;
}
Use these two interfaces, you can fully customize MyBatis of transactions.
dataSsource
dataSource elements using the basic JDBC data source interface to configure the JDBC connection object resources.
 Many MyBatis application examples will be by example, to configure the data source. However, it is not necessary. To know in order to facilitate the use of lazy loading, data source is required.
There are three built-in data source types (ie type ="???"):
UNPOOLED - this data source implementation is simple and each is requested to open and close the connection. It is a bit slow, this is the simple application of a good choice because it does not require timely connections available. Different database on the performance is not the same, so some database data source is not important for the configuration, this configuration is idle.
UNPOOLED type of data source that is used to configure the following 4 attributes:
 driver - JDBC driver which is the fully qualified Java class name (if your driver included, nor is it the data source class.)
 url - this is the database JDBC URL address.
 username - the database login user name.
 password - login password for the database.
 defaultTransactionIsolationLevel - the default connection transaction isolation level.
As an option, you can pass database-driven attributes. To do this, the prefix attribute is the "driver." At the beginning, for example:
 driver.encoding = UTF8
This will pass by value "UTF8" to pass attribute "encoding", it is through the DriverManager.getConnection (url, driverProperties) method is passed to the database driver.
POOLED - This is the JDBC connection object data source connection pool implementation, to avoid creating a new instance of the necessary connection to the initial connection and authentication time. This is a current Web application used to quickly respond to requests very popular method.
In addition to the above (UNPOOLED) of the property, there are many attributes can be used to configure the POOLED data source:
 poolMaximumActiveConnections - existing activities at any time (that is being used) the number of connections. Default: 10
 poolMaximumIdleConnections - any time there is idle connections.
 poolMaximumCheckoutTime - being forced to return before the connection pool is the inspection time. Default: 20000 milliseconds (ie 20 seconds)
 poolTimeToWait - This is a print log to the pool of low-level state of the opportunity set, as well as try to obtain access, these cases often take a long time (to avoid when the connection pool is not configured to silently fail.) Default: 20000 milliseconds (ie 20 seconds)
 poolPingQuery - the detection of inquiry sent to the data used to verify the connection is working properly and ready to accept requests. The default is "NO PING QUERY SET", this will cause a lot of database-driven connected by an error message and cause failure.
 poolPingEnabled - it is open or disable the detection query. If enabled, you must use a valid SQL statement (preferably very fast) set poolPingQuery property. Default: false.
 poolPingConnectionsNotUsedFor - This is the time to configure poolPingQuery be used many times again. This can be set to match the standard database connection timeout time, to avoid unnecessary detection. Default: 0 (that is, all connections are detected each time - but just as true when poolPingEnabled when applicable).
JNDI - this data source implementation is to use Spring or application servers such as container, the container can be centralized or in an external configuration data source, and then place a JNDI context reference. The data source configuration requires only two attributes:
 initial_context - This attribute is used to find the environment from the initial context (that is initialContext.lookup (initial - context)). This is an optional attribute, if ignored, then the property will be directly data_source initialContext background search again.
 data_source - This is a reference to an instance of the data source location of the path of the context. It will be returned by the query environment initial_context background to find, if initial_context does not return the results directly to the initial context to look for the environment.
And other similarly configured data source, it can also be called "env." Prefix sent directly to the initial context properties. For example:
 env.encoding = UTF8
After initialization, this will be the value of the "UTF8" to pass the initial context constructor called "encoding" attribute.
mappers
Since the behavior of MyBatis configuration has been done by the above-mentioned elements, we now must define a SQL Map statement. But first we need to tell MyBatis where to look to these statements. Java in this regard does not provide a good way, so the best way is to tell MyBatis where to find map file. You can use the class path resources relative to the reference, or character representation, or the fully qualified name of url references (including file: / / / URLs). For example:
/ / 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>
These statements simply tell MyBatis where to find map file. The remaining detail is in each SQL Map file, the following section we discuss the SQL mapping file.
SQL Map XML files
MyBatis real power is in the mapping statement. This is a miracle takes place. For all the strength, SQL map XML files is quite simple. Of course, if you will they and other functions of the JDBC code to compare, you will find map file saves about 95% of the amount of code. MyBatis Construction is focused on SQL, so far from the ordinary way.
SQL mapping files have a very few top-level elements (should be defined according to their order):
 cache - configuration for a given namespace cache.
 cache-ref - references from other namespaces cache configuration.
 resultMap - the most complex and most powerful element, is used to describe how the result set from the database to load your object.
 parameterMap - has been abandoned! Old-style parameter mapping. Inline parameters are preferred, this element may be removed in the future. There will not be recorded.
 sql - SQL blocks can be reused, other statements can also be referenced.
 insert - insert statement mapping  update - Maps update statement  delete - map delete statement  select - mapping from the next part of the query statement itself begins to describe the details of each element.
select
MyBatis query is to use one of the most common elements. Until you remove the data from the database only when the data stored in a database that is how valuable, so many applications query the data much more than change. For each insert, update, or delete, it will be a lot of inquiries. This is a basic principle of MyBatis is to focus and effort into the cause of mapping queries and results. Elements of simple types of query is very simple. For example:
<select"selectPerson" parameterType="int" resultType="hashmap">
SELECT * FROM PERSON WHERE ID = # {id}
</ Select>
This statement is called selectPerson, use a int (or Integer) type of parameter and returns a HashMap type object, in which the key is the column name, value is the value of the corresponding column.
Attention parameter Notes:
# {Id}
This tells MyBatis create a prepared statement parameters. Use JDBC, such a parameter in the SQL, by a "?" To identify, and was passed to a new prepared statement, like this:
/ / Similar JDBC code, NOT MyBatis ...
String selectPerson = "SELECT * FROM PERSON WHERE";
PreparedStatement ps = conn.prepareStatement (selectPerson);
ps.setInt (1, id);
Of course, this requires a lot of single JDBC code to extract the results and map them to the object instance, this is the place MyBatis save you time. We need to understand the parameters and results mapping. Some of those details we have to understand the following.
select element allows you to configure many attributes to determine the role of the details of each statement.
<Select
id = "selectPerson"
parameterType = "int"
parameterMap = "deprecated"
resultType = "hashmap"
resultMap = "personResultMap"
flushCache = "false"
useCache = "true"
timeout = "10000"
fetchSize = "256"
statementType = "PREPARED"
resultSetType = "FORWARD_ONLY"
> Property Description
id
Only in the namespace identifier can be used to refer to this statement.
parameterType
This statement will be passed in the parameters of the fully qualified class name or alias.
parameterMap
This is a reference to an external parameterMap The method has been abandoned. Inline parameter mapping and parameterType properties.
resultType
From this type of statement is expected to return fully qualified class name or alias. Note that the collection case, it should be the type of collection can contain, and can not set itself. Use resultType or resultMap, but not both.
resultMap
Named reference external resultMap. Back to map the characteristics of a MyBatis most power because they have a good understanding of the case, many complex mapping situations can be resolved. Use resultMap or resultType, but not both.
flushCache
Set it to true, regardless of when the statement was taken by Oh, will cause the cache to be cleared. Default: false.
useCache
Set it to true, will lead to the result of this statement to be cached. Default: true.
timeout
This set, the driver returns the database request to wait for results, and the maximum waiting time of an exception value. Default not set (driver to handle.)
fetchSize
It is implied every time the driver returns the results of batch number of rows. Default not set (driver to handle.)
statementType
STATEMENT, PREPARED or CALLABLE kind. This will make MyBatis use choose to use the Statement, PreparedStatement or CallableStatement. Default: PREPARED.
resultSetType
FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE in one. The default is not set (driver to handle.)
insert, update, delete
Data change statement, insert, update and delete in their implementation is very similar:
<Insert
id = "insertAuthor"
parameterType = "domain.blog.Author"
flushCache = "true"
statementType = "PREPARED"
keyProperty = ""
useGeneratedKeys = ""
timeout = "20000">
<Update
id = "insertAuthor"
parameterType = "domain.blog.Author"
flushCache = "true"
statementType = "PREPARED"
timeout = "20000">
<Delete
id = "insertAuthor"
parameterType = "domain.blog.Author"
flushCache = "true"
statementType = "PREPARED"
timeout = "20000"> attribute description
id
Only in the namespace identifier can be used to refer to this statement.
parameterType
This statement will be passed in the parameters of the fully qualified class name or alias.
parameterMap
This is a reference to an external parameterMap The method has been abandoned. Inline parameter mapping and parameterType properties.
flushCache
Set it to true, regardless of when the statement was taken by Oh, will cause the cache to be cleared. Default: false.
timeout
This set, the driver returns the database request to wait for results, and the maximum waiting time of an exception value. Default not set (driver to handle.)
statementType
STATEMENT, PREPARED or CALLABLE kind. This will make MyBatis use choose to use the Statement, PreparedStatement or CallableStatement. Default: PREPARED.
useGeneratedKeys
(Insert only useful) This will tell MyBatis way to use JDBC's getGeneratedKeys out by the data (for example: such as MySQL and SQL Server database management system, auto-increment field) within the generated primary key. Default: false.
keyProperty
(Insert only useful) mark a property, MyBatis Council passed getGeneratedKeys or by child elements insert statement selectKey set its value. Default: not set.
Here is the insert, update and delete statements example:
<insert parameterType="domain.blog.Author">
insert into Author (id, username, password, email, bio)
values (# {id}, # {username}, # {password}, # {email}, # {bio})
</ Insert>
<update parameterType="domain.blog.Author">
update Author set
username = # {username},
password = # {password},
email = # {email},
bio = # {bio}
where id = # {id}
</ Update>
<delete"deleteAuthor" parameterType="int">
delete from Author where id = # {id}
</ Delete>
As mentioned above, insert the statement a little more, it has some attributes and child elements to handle primary key generation.
First, if your database supports auto-generated primary key fields (such as MySQL and SQL Server), then you can set useGeneratedKeys = "true", but you have to do to set keyProperty to target property. For example, if the above table has been on the Author used the automatically generated id column type, then the statement can be amended as follows:
<Insert parameterType = "domain.blog.Author"
useGeneratedKeys = "true" keyProperty = "id">
insert into Author (username, password, email, bio)
values (# {username}, # {password}, # {email}, # {bio})
</ Insert>
MyBatis there is another way to handle the database does not support the automatic generation of types, or may JDBC driver does not support automatic generation of primary key primary key generation problem.
Here is a simple (or even silly) example, it can generate a random ID (you may not do, but it shows the flexibility of MyBatis deal with the problem, because it does not really care about the generation ID):
<insert parameterType="domain.blog.Author">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST (RANDOM () * 1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</ SelectKey>
insert into Author
(Id, username, password, email, bio, favourite_section)
values
(# {Id}, # {username}, # {password}, # {email}, # {bio},
# {FavouriteSection, jdbcType = VARCHAR}
)
</ Insert>
In the above example, selectKey element will be the first run, Author of the id is set, then insert the statement will be called. This gives you a simple act in your database to handle the auto-generated primary key, without the need to make your Java code more complicated.
selectKey elements described as follows:
<SelectKey
keyProperty = "id"
resultType = "int"
order = "BEFORE"
statementType = "PREPARED"> attribute description
keyProperty
selectKey statement results should be set to the target attribute.
resultType
Type of the result. MyBatis can usually be calculated, but the writing is also no problem. MyBatis allow any simple type as the primary key types, including strings.
order
This can be set to BEFORE or AFTER. If set to BEFORE, then it will first select the primary key, set keyProperty then insert statement. If set to AFTER, then the first insert statement, then selectKey elements - such as the Oracle database, this and similar statements can be embedded into the sequence of call.
statementType
And in front of the same, MyBatis support STATEMENT, PREPARED and CALLABLE statement mapping types, representing the PreparedStatement and CallableStatement type.
sql
This element can be used to define reusable SQL code, can be included in the other statement. For example:
<sql"userColumns"> id, username, password </ sql>
The SQL fragment can be included in other statements, such as:
<select"selectUsers" parameterType="int" resultType="hashmap">
select <include refid="userColumns"/>
from some_table
where id = # {id}
</ Select>
Parameters
In the previous statement, you've seen some examples of simple parameters. In MyBatis the argument is very powerful element. For the simple practice, about 90% of the cases, is not too much, such as:
<select"selectUsers" parameterType="int" resultType="User">
select id, username, password
from users
where id = # {id}
</ Select>
The above example shows a very simple mapping of named parameters. Parameter type is set to "int", so this parameter can be set to anything. Native type or simple data types, such as integer and string is not properties, so it will be completely replaced with the parameters. However, if you pass a complex object, then MyBatis approach will have a little different. For example:
<insert"insertUser" parameterType="User">
insert into users (id, username, password)
values (# {id}, # {username}, # {password})
</ Insert>
If the User object type parameter is passed to the statement, id, username and password attributes will be searched, and their values to be passed to the parameters of prepared statements.
This is for passing parameters to the statement very good. But there are also some other parameter mapping features.
First, like the rest of MyBatis, parameters can specify a certain data type.
# {Property, javaType = int, jdbcType = NUMERIC}
Like the rest of MyBatis, javaType parameter object can usually come from the top, unless the object is a HashMap. JavaType should be determined so to ensure the correct type of processor.
Note: If null is passed as a value for all columns may be empty, JDBC Type is required. To be yourself by reading prepared statements setNull () method to study the JavaDocs documentation.
To customize the type of processor, you can specify a certain type of processor class (or alias), for example:
# {Age, javaType = int, jdbcType = NUMERIC, typeHandler = MyTypeHandler}
Although it looks complicated, but actually you have very little to set them one of them.
For numeric type, for determining how many numbers are related, there is a range of values.
# {Height, javaType = double, jdbcType = NUMERIC, numericScale = 2}
Finally, mode attribute allows you to specify the IN, OUT or INOUT parameters. If the parameter is OUT or INOUT, the true value of the parameter object properties will be changed, just as you expect you need your output parameters. If the mode is OUT (or INOUT), and jdbcType the CURSOR (that is, Oracle's REFCURSOR), you must specify a resultMap to map the result set to the parameter type. To note that the javaType attribute is optional, if left blank is jdbcType the CURSOR type, it will automatically be set to the result set.
# {Department,
mode = OUT,
jdbcType = CURSOR,
javaType = ResultSet,
resultMap = departmentResultMap}
MyBatis also supports many advanced data types, such as structure, but when up out parameters, you must tell the statement type name. For example (again suggest that in practice do not like this line):
# {MiddleInitial,
mode = OUT,
jdbcType = STRUCT,
jdbcTypeName = MY_TYPE,
resultMap = departmentResultMap}
While all these powerful options many times you simply specify the attribute name, MyBatis will own the remaining calculations. Most of the cases is that you may be empty for the jdbcType specify the column names.
# {FirstName}
# {MiddleInitial, jdbcType = VARCHAR}
# {LastName}
Replace a string by default, use the format # {} syntax will lead to MyBatis property and to create a prepared statement to set the security context of its value (such as?). That it is very safe, very quickly is the preferred approach, sometimes you just want to insert directly in the SQL statement does not change a string. For example, like ORDER BY, you can use this:
ORDER BY $ {columnName}
Here MyBatis not modify or escape string.
Important: to accept the contents of the output from the user and provide a statement in the same string, this is unsafe. This will lead to a potential SQL injection attacks, so you should not allow the user to enter these fields, or often and check their own escape.
resultMap
resultMap MyBatis the most important element is the most powerful elements. It is to make you stay away from the needs of 90% of the data from the JDBC result set out the code that thing, and in some cases allow you to do some things that do not support JDBC. In fact, the preparation of the joint statement similar to the complex mapping these same code, it may be across thousands of lines of code. ResultMap design is simple and clear results statements do not need maps, but does require a lot of complex statements describe their relationship.
You have already seen an example of a simple mapping statement, but no clear resultMap. For example:
<select"selectUsers" parameterType="int" resultType="hashmap">
select id, username, hashedPassword
from some_table
where id = # {id}
</ Select>
Such a statement is simply acting on all the columns are automatically mapped to keys on a HashMap, which by the resultType attribute. This is useful in many cases, but not well HashMap describe a domain model. That your application will use JavaBeans or POJOs (Plain Old Java Objects, ordinary Java objects) as a domain model. MyBatis to both support. Consider the following JavaBean:
package com.someapp.model;
public class User {
private int id;
private String username;
private String hashedPassword;
public int getId () {
return id;
}
public void setId (int id) {
this.id = id;
}
public String getUsername () {
return username;
}
public void setUsername (String username) {
this.username = username;
}
public String getHashedPassword () {
return hashedPassword;
}
public void setHashedPassword (String hashedPassword) {
this.hashedPassword = hashedPassword;
}
}
JavaBean-based specification, the above class has three attributes: id, username and hashedPassword. These statements may select an exact match to the column name.
Such a JavaBean can be mapped to the result set is as simple as mapped to the HashMap.
<Select "selectUsers" parameterType = "int"
resultType = "com.someapp.model.User">
select id, username, hashedPassword
from some_table
where id = # {id}
</ Select>
To remember the type alias is your partner. You can not use them to enter the full path to the class. For example:
<! - In Config XML file ->
<typeAlias type="com.someapp.model.User" alias="User"/>
<! - In SQL Mapping XML file ->
<Select "selectUsers" parameterType = "int"
resultType = "User">
select id, username, hashedPassword
from some_table
where id = # {id}
</ Select>
Under these circumstances, MyBatis automatically in the background to create a ResultMap, based on the property name to map out the properties of the JavaBean. If you do not exactly match the column names, column names you can select words to use an alias (a basic SQL features) to match the label. For example:
<select"selectUsers" parameterType="int" resultType="User">
select
user_id as "id",
user_name as "userName",
hashed_password as "hashedPassword"
from some_table
where id = # {id}
</ Select>
ResultMap the best place you've learned a lot, but you have not really seen one. These simple examples do not need more than what you see. For example, just because, let's take a look at the last example is what resultMap outside, which is to resolve the column names do not match the other way.
<resultMap type="User">
<id property="id" column="user_id" />
<result property="username" column="username"/>
<result property="password" column="password"/>
</ ResultMap>
The statements refer to it using the resultMap property on the line (note that we removed the resultType property). For example:
<Select "selectUsers" parameterType = "int"
resultMap = "userResultMap">
select user_id, user_name, hashed_password
from some_table
where id = # {id}
</ Select>
If the world is always so simple.
Advanced resulting map
MyBatis created an idea: The database is not always what you want or need what they are. Our favorite is the third best database paradigm or BCNF mode, but they sometimes are not. If possible have a separate database mapping, all applications can use it, it is very good, but sometimes no. Resulting map is MyBatis provide the answer to deal with this problem.
For example, how do we map the following statement?
<! - Very Complex Statement ->
<Select parameterType = "int"
resultMap = "detailedBlogResultMap">
select
B.id as blog_id,
B.title as blog_title,
B.author_id as blog_author_id,
A.id as author_id,
A.username as author_username,
A.password as author_password,
A.email as author_email,
A.bio as author_bio,
A.favourite_section as author_favourite_section,
P.id as post_id,
P.blog_id as post_blog_id,
P.author_id as post_author_id,
P.created_on as post_created_on,
P.section as post_section,
P.subject as post_subject,
P.draft as draft,
P.body as post_body,
C.id as comment_id,
C.post_id as comment_post_id,
C.name as comment_name,
C.comment as comment_text,
T.id as tag_id,
T.name as tag_name
from Blog B
left outer join Author A on B.author_id = A.id
left outer join Post P on B.id = P.blog_id
left outer join Comment C on P.id = C.post_id
left outer join Post_Tag PT on PT.post_id = P.id
left outer join Tag T on PT.tag_id = T.id
where B.id = # {id}
</ Select>
You may want to map it to a smart object model, including an author was writing a blog, a lot of stuff, and each zero or multiple Bowen's comments and tags. Here is a complete example of the complexity of mapping the results (assuming the author, blog, blog posts and comments and tags are the type of alias.) We take a look, but do not worry, we will go step by step instructions. The first day it looks daunting, but in fact very simple.
<! - Very Complex Result Map ->
<resultMap type="Blog">
<constructor>
<idArg column="blog_id" javaType="int"/>
</ Constructor>
<result property="title" column="blog_title"/>
<association property="author" column="blog_author_id" javaType=" Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
<result property="bio" column="author_bio"/>
<result property="favouriteSection" column="author_favourite_section"/>
</ Association>
<collection property="posts" ofType="Post">
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
<Association property = "author" column = "post_author_id"
javaType = "Author" />
<collection property="comments" column="post_id" ofType=" Comment">
<id property="id" column="comment_id"/>
</ Collection>
<collection property="tags" column="post_id" ofType=" Tag">
<id property="id" column="tag_id"/>
</ Collection>
<discriminator javaType="int" column="draft">
<case value="1" resultType="DraftPost"/>
</ Discriminator>
</ Collection>
</ ResultMap>
There are many sub-elements resultMap element and a structure worthy of discussion. Here is the concept of the view element resultMap
resultMap
 constructor - class instantiation is used to inject the result into the constructor  idArg - ID parameter; results as the ID tag can help improve the overall performance  arg - injected into the constructor of a general result  id - an ID results; results as the ID tag can help improve the overall performance  result - injected into the field or JavaBean property of the general results  association - a complex type of association; many results will package the results into a map of this type  embedding - mapping the results of their own association, or refer to a  collection - a complex type of the result set  embedded map - map their own set of results, or reference to a  discriminator - to use the resulting value to decide which results map  case - the result of mapping based on certain values embedded in the results of mapping  - This situation results map itself, it can contain many of the same element, or it can refer to the results of an external mapping.
Best Practices: Usually gradual establishment of the results map. Unit testing really help here. If you try to create a way to create a great example to the above, the results of mapping, then there may be errors and difficult to control it to work. Start easier, step by step development. And to conduct unit test! Disadvantage of using this framework is that they sometimes black box (if visible source code.) Are you sure you want to act to achieve the best choice is to write unit tests. It can also help you get an error when submitted.
The following section will detail each element.
id, result
<id property="id" column="post_id"/>
<result property="subject" column="post_subject"/>
These are the results of mapping the most basic content. id and the result is a single column values map to a simple data types (string, integer, double precision floating point number, date, etc.) of the individual properties or fields.
The only difference between the two is the id that the result will be used when comparing the identity of an object instance attribute. This helps to improve overall performance, particularly in the results cache and embedded maps (that is, the joint mapping).
Each has some attributes:
Property Description
property
Mapped out the results of the field or property. If the match exists, and given the JavaBeans properties of the same name, it will use. Otherwise MyBatis will look for the given name field. Both of these situations are usually point you can use the complex nature of navigation. For example, you can map a number of things: "username", or mapped to some complex things: "address.street.number".
column
Obtained from the database column names, or rename the column name tags. This is usually passed to the resultSet.getString (columnName) method parameters in the same string.
javaType
A fully qualified Java class name, or a type alias (an alias to participate in the above list of built-in type.) If you mapped to a JavaBean, MyBatis can usually determine the type. However, if you mapped to the HashMap, then you should explicitly specify the javaType to ensure the desired behavior.
jdbcType
In the following table types supported by the JDBC type of the list. JDBC type is only need to insert, update, and delete operations may be processed for the empty columns. This is the JDBC needs, rather than MyBatis's. If you directly use JDBC programming, you need to specify the type - but only on the value may be empty.
typeHandler
We discussed earlier the default type of processor. Using this property, you can override the default type of processor. This property value is the fully qualified class name or a type of processor to achieve, or the type of alias.
Supported JDBC type for future reference, MyBatis enumerated by including the jdbcType, supports the following JDBC types.
BIT
FLOAT
CHAR
TIMESTAMP
OTHER
UNDEFINED
TINYINT
REAL
VARCHAR
BINARY
BLOB
NVARCHAR
SMALLINT
DOUBLE
LONGVARCHAR
VARBINARY
CLOB
NCHAR
INTEGER
NUMERIC
DATE
LONGVARBINARY
BOOLEAN
NCLOB
BIGINT
DECIMAL
TIME
NULL
CURSOR
Structure
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of MyBatis User's Guide

  • extjs development environment set up and practice

    1, download and extract the extjs 2, download eclipse and Eclipse AJAX Toolkit Framework (ATF) I have been accustomed to using eclipse as a development environment, a variety of open-source plugin so that eclipse has all-around performance, operating effi

  • hibernate Technical Study Notes (first)

    Introduction: Model does not match (impedance mismatch) java object-oriented language, object model, its key concepts are: inheritance, association, polymorphism, etc.; database is the relational model, its key concepts are: tables, primary keys, for ...

  • Rails2.0.2 change the default DB adpter

    In Rails2.0.2 rails demo ... ... MissingSourceFile in SayController # hello no such file to load - sqlite3 RAILS_ROOT: / home / kenb / rails-projects / demo ... ... Checked config / database.yml, adpter default is set become the sqlite3. Check the ra ...

  • ROR resources

    Ruby Web site resources: ruby official website: http://www.ruby-lang.org ruby doc official website: http://www.ruby-doc.org rubyonrails official website: http://www.rubyonrails.org programming ruby online edition (Ruby studying the "Bible") ...

  • Use Ext JS to read the JsonReader complex object json

    Today was how to resolve the following complex json object to the difficult living over a long time .. did not find documentation how to read JsonReader Ways json object (possibly also because of their limited level of E the text did not correctly underst

  • NoClassDefFoundError: javax / servlet / Servlet

    In the project in order to achieve a listener in web.xml set up a listener, did start in Tomcat actually occurred after java.lang.NoClassDefFoundError: javax / servlet / ServletContextListener this anomaly google and found the reasons for the lack of serv

  • hibernate using c3p0 connection pooling

    Private http://www.lifevv.com/tenyo/doc/20070605102040991.html c3p0 for open source's JDBC connection pool, with the release hibernate. This article describes how to use the hibernate configuration in c3p0. c3p0 connection pool configuration is v ...

  • Hibernate configuration parameters hibernate.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

  • In the servlet use Bean

    According to Sun's definition, JavaBean is a reusable software components. In fact JavaBean is a Java class, through the package into a property and methods of treatment of a function or a business object, referred to as bean. Because JavaBean is ...

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries