Core objects of MyBatis:
Each MyBatis-based application is centered on an instance of Sqlsessionfactory. Examples of sqlsessionfactory can be obtained by
Sqlsessionfactorybuilder obtained. Sqlsessionfactorybuilder, however, can be from an XML configuration file or a pre-defined
Example constructs an instance of Sqlsessionfactory.
The method of invoking a Java object using a fully qualified name is similar, and there is a reason for doing so. This name can be mapped directly into the namespace
The Mapper class with the same name, and matches the name, argument, and return type in the mapped SELECT statement into a method.
Namespaces (namespaces) are optional in previous versions of MyBatis, and are therefore of no benefit because they are prone to confusion. Now the namespace is a must, the target
is to be able to differentiate statements further than simply using longer, fully qualified names.
Their mapped statements can be done without XML, taking the
It is possible to use Java annotations:
@select ("select * from test_table where Id=#{id}")
public void get ();
Focus:
Scope (scope) and life cycle
It is important to understand the different ranges and life cycle classes that we have discussed so far, because the use of errors can lead to very serious concurrency problems.
The dependency injection framework can create thread-safe, transaction-based sqlsession and Mappers (mapper) and inject them directly into your bean, so you can directly ignore their lifecycle. If you are interested in how to use MyBatis through a dependency injection framework, you can study mybatis-spring or Mybatis-guice two
Sub-project.
Sqlsessionfactorybuilder
This class can be instantiated, used, and discarded, and once the sqlsessionfactory is created, it is no longer needed. So the Sqlsessionfactorybuilder instance is the most
The good range is the method scope (that is, the local method variable). You can reuse Sqlsessionfactorybuilder to create multiple sqlsessionfactory instances, but the most
Well, don't let it always exist to ensure that all XML parsing resources are open to more important things.
Sqlsessionfactory
Once created, it should exist for the duration of the application and there is no reason to clean it up or rebuild it. Using the Sqlsessionfactory
The best practice is not to repeatedly create multiple times during an app run, and rebuilding sqlsessionfactory multiple times is considered a code "bad smell". So
The optimum range of Sqlsessionfactory is the range of applications.
Sqlsession
Each thread should have its own sqlsession instance. The sqlsession instance is not thread-safe and therefore cannot be shared, so the best range for it is please
The scope of the request or method. You must never put a reference to a sqlsession instance in a static domain of a class, or even an instance variable of a class. And never be able to sqlsession the real
Examples are referenced in any type of management scope, such as HttpSession in the Serlvet schema.
A mapper is an interface that is created to bind a map statement. An instance of the Mapper interface is obtained from the sqlsession. So technically speaking, the maximum range of mapper instances is
Same as sqlsession, because they are all requested from the sqlsession. However, the best range of mapper instances is the method scope.
A description of the configuration file for MyBatis:
The MyBatis configuration file contains settings (settings) and attribute information that affect MyBatis behavior very deeply. The top-level structure of the document is as follows:
Setting: Setting
Multipleresultsetsenabled (whether a single statement is allowed to return a multi-result set (requires a compatible driver))
By opening the connection pool when you configure it:
Jdbcdriver Drive Configuration
&allowmultiqueries=true (querying with multiple result sets)
? useunicode=true&characterencoding=utf-8
Defaultexecutortype:
Configure the default execution
Manager Simple is the
The actuator of the pass;
The reuse actuator will weigh
Using Preprocessing statements
(Prepared
statements);
The BATCH executor will re-
Use statements and perform batch
Update.
Proxyfactory (Specifies that MyBatis creates the proxy tool with deferred objects, which is Cgli by default): You can also choose to use Java native javassit)
Typealiases (Type alias)
A type alias is a short name set for the Java type. It is only relevant to the XML configuration, and it only exists to reduce the redundancy of the fully qualified name of the class.
<typeAliases>
<package name= "Domain.blog"/>
</typeAliases>
Each Java bean in the package domain.blog, without annotations, uses the Bean's first lowercase unqualified class name as its alias. Like what
The alias of Domain.blog.Author is Author; if there is an annotation, the alias is its annotation value. Look at the following example:
@Alias ("author")
public class Author {
...
}
Typehandlers (Type processor)
Whether MyBatis sets a parameter in a preprocessing statement (PreparedStatement) or extracts a value from the result set, the type processor is used to obtain
The value is converted to the Java type in the appropriate way. The following table describes some of the default types of processors.
You can override the type processor or create your own type processor to handle unsupported or nonstandard types. The specific approach is: to achieve
Org.apache.ibatis.type.TypeHandler interface, or inherit a convenient class Org.apache.ibatis.type.BaseTypeHandler, and then optionally
To map it to a JDBC type. Like what:
Using this type processor will overwrite the type processor that already exists for the String type property and the VARCHAR parameter and result of processing Java. Pay attention to MyBatis
Does not pry into the database meta-information to determine which type to use, so you must indicate in the parameter and result mappings that it is a VARCHAR type field so that it can be bound to the positive
On the type processor. This is because: MyBatis is not clear about the data type until the statement is executed.
Add a Javatype attribute (for example: Javatype= "String") on the configuration element of the type processor (Typehandler elements);
Add a @MappedTypes annotation on the class of the type processor (Typehandler Class) to specify the list of Java types associated with it. If the
The Javatype attribute is also specified, the annotation mode is ignored.
There are two ways to specify the JDBC type that is associated:
Add a Javatype attribute on the configuration element of the type processor (for example: Javatype= "VARCHAR");
Add a @MappedJdbcTypes annotation on the class of the type processor (Typehandler Class) to specify a list of JDBC types associated with it. If the
The Javatype attribute is also specified, the annotation mode is ignored.
Object Factory (Objectfactory):
MyBatis each time a new instance of the resulting object is created, it is done using an object factory (objectfactory) instance. The default object factory needs to do is simply
Instantiate the target class, either through the default constructor, or by way of a parameter constructor when the parameter mapping exists. If you want to override the default behavior of the object factory,
This can be done by creating your own object factory.
Plugins (plugins)
MyBatis allows you to intercept calls at a point during the execution of a mapped statement. By default, MyBatis allows method calls that use plug-ins to intercept include:
Executor (update, query, Flushstatements, Commit, rollback, gettransaction, close, isClosed)
Parameterhandler (Getparameterobject, Setparameters)
Resultsethandler (Handleresultsets, Handleoutputparameters)
Statementhandler (Prepare, parameterize, batch, update, query)
The details of the methods in these classes can be found by looking at the signature of each method, or by looking directly at the source code in the MyBatis's release package. Let's say you want to do more than just monitor
method is called, then you should be well aware of the behavior of the method being overridden. Because if you try to modify or override the behavior of an existing method, you are likely to be destroying
MyBatis's core module. These are the lower classes and methods, so be careful when using plugins.
With the powerful mechanism provided by MyBatis, the use of plug-ins is very simple, just implement the Interceptor interface and specify the method signature you want to intercept.
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) {
}
}
<!--Mybatis-config.xml--
<plugins>
<plugin interceptor= "Org.mybatis.example.ExamplePlugin" >
<property name= "Someproperty" value= "/>"
</plugin>
</plugins>
The plug-in above will intercept all "update" method calls in the Executor instance, where Executor is the internal object responsible for executing the low-level mapping statement.
Configuration environment (environments)
MyBatis can be configured to adapt to a variety of environments, a mechanism that helps to apply SQL mapping to multiple databases, and there are a number of reasons for this to happen. For example
Development, test, and production environments require different configurations, or multiple production databases that share the same Schema, and you want to use the same SQL mappings.
Transaction manager (TransactionManager)
There are two types of transaction managers in MyBatis (that is, type= "[jdbc| MANAGED] "):
jdbc– This configuration is the direct use of the JDBC commit and rollback settings, which depend on the connection from the data source to manage the transaction scope.
managed– this configuration almost nothing. It never commits or rolls back a connection, but instead lets the container manage the entire life cycle of the transaction (such as the JEE application server
's context). By default it closes the connection, but some containers do not want it, so you need to set the CloseConnection property to False to prevent it from being silently
The shutdown behavior.
Note:
If you are using Spring + MyBatis, it is not necessary to configure the transaction manager because the Spring module uses its own manager to overwrite the previous configuration.
Neither of these transaction manager types requires any properties
Any attributes configured in XML will be passed to the SetProperties () method after instantiation. You also need to create an implementation class for the Transaction interface, which
The mouth is also very simple:
Public interface Transaction {
Connection getconnection () throws SQLException;
void commit () throws SQLException;
void rollback () throws SQLException;
void Close () throws SQLException;
}
The DataSource element uses the standard JDBC data source interface to configure the resources of the JDBC Connection object.
Many MyBatis applications will configure the data source as exemplified in the example. However, it is not necessary. You know, to facilitate the use of lazy loading, the data source is a must
Of
There are three types of built-in data sources (i.e. type= "[unpooled| pooled| JNDI] "):
XML file for Mapper:
Few top-level elements of the SQL mapping file: The most important of these are the RESLUTMAP elements:
Reslutmap: Is the most complex and the most powerful element in MyBatis, used to describe how objects are loaded from the result set;
sql– A reusable statement block that can be referenced by other statements.
<select id= "Selectperson" parametertype= "int" resulttype= "HashMap" >
SELECT * from person WHERE ID = #{id}
</select>
This statement is called Selectperson, takes an int (or Integer) type parameter, and returns an object of type HashMap, where the key is the column name, the value
is the corresponding value in the result row.
The Select element has many properties that allow you to configure the details of each statement's function.
<select
Id= "Selectperson"
parametertype= "int"
parametermap= "Deprecated"
Resulttype= "HashMap"
resultmap= "Personresultmap"
Flushcache= "false"
Usecache= "true"
Timeout= "10000"
Fetchsize= "256"
Statementtype= "PREPARED"
Resultsettype= "Forward_only" >
In order to interpret:
1. A unique identifier in the namespace that can be used to refer to this statement.
2. The fully qualified name or alias of the parameter class that will pass in the statement. This property is optional because MyBatis can infer the parameters of the specific incoming statement through Typehandler, and the default value is unset.
3. The fully qualified name or alias of the class of the expected type returned from this statement. Note that if it is a collection case, it should be the type that the collection can contain, not the collection itself. Use Resulttype or Resultmap, but not at the same time.
4. Naming references for external resultmap. The mapping of result sets is the most powerful feature of MyBatis, with a good understanding of it, many complex mappings
The shooting situation can be solved. Use Resultmap or Resulttype, but not at the same time.
5. Set it to true that any time the statement is called, both the local cache and the level two cache will be emptied, with the default value: False.
6. Setting it to true causes the result of this statement to be cached by level two, the default value: True for the SELECT element.
7. This setting is the number of seconds the driver waits for the database to return request results before throwing an exception. Default value is unset (dependent driver)
8. This is an attempt to affect the number of results per batch returned by the driver and the value of this setting is equal. The default value is unset (dependent driver).
One of the 9.statement,prepared or callable. This will allow MyBatis to use separate
Statement,preparedstatement or CallableStatement, default value: PREPARED.
10. If Databaseidprovider,mybatis is configured, it will load all statements without databaseId or matching the current databaseId;
If there is a statement with or without, it is ignored.
11. This setting applies only to nested results SELECT statements: If True, the assumption is that nested result sets or groupings are included, so that when a main result row is returned, there is no case of a reference to the preceding result set. This makes it possible to get a nested result set without causing enough memory. Default value: False
<insert
Id= "Insertauthor"
Parametertype= "Domain.blog.Author"
Flushcache= "true"
Statementtype= "PREPARED"
Keyproperty= ""
Keycolumn= ""
Usegeneratedkeys= ""
Timeout= ">"
ParameterType: The fully qualified class name or alias of the parameter that will pass in the statement. This property is optional because MyBatis can infer the parameters of the specific incoming statement through Typehandler, and the default value is unset.
Usegeneratedkeys:
(Only useful for insert and update) This will enable MyBatis to use the JDBC Getgeneratedkeys method to remove the data from the
(for example, an auto-increment field for a relational database management system such as MySQL and SQL Server), the default value:
False
<sql id= "SomeTable" >
${prefix}table
</sql>
<sql id= "Someinclude" >
From
<include refid= "${include_target}"/>
</sql>
<select id= "Select" resulttype= "Map" >
Select
Field1, Field2, field3
<include refid= "Someinclude" >
<property name= "prefix" value= "Some"/>
<property name= "Include_target" value= "sometable"/>
</include>
</select>
Parameters (Parameters):
<insert id= "Insertuser" parametertype= "User" >
INSERT into users (ID, username, password)
VALUES (#{id}, #{username}, #{password})
</insert>
If a Parameter object of type User is passed to the statement, the ID, username, and password properties will be looked up and their values passed into the parameters of the preprocessing statement
In
This is a good and simple way to pass arguments to a statement, but the function of parameter mapping is much more than that.
First, like other parts of MyBatis, parameters can also specify a special data type.
#{property,javatype=int,jdbctype=numeric}
Like the rest of MyBatis, javatype can usually be determined from the parameter object, provided that the object is not a HashMap. Then javatype should be determined to ensure that the correct type of processor is used.
If NULL is passed as a value, the JDBC Type is required for all columns that may be empty. You can do it yourself by reading the SetNull () method of the preprocessing statement
JavaDocs documentation to investigate this situation.
For numeric types, there is also a setting for the number of decimal reserved digits to determine the number of digits retained after the decimal point.
#{height,javatype=double,jdbctype=numeric,numericscale=2}
String substitution
By default, syntax using the #{} format causes MyBatis to create preprocessing statement properties and safely set values (such as?). This is safer, more rapid, and usually
Preferred approach, but sometimes you just want to insert a non-changing string directly into the SQL statement. For example, like ORDER by, you can use this:
ORDER by ${columnname} Here MyBatis does not modify or escape the string.
Key parts:
The design of RESULTMAPS:RESULTMAP is that simple statements do not require explicit result mappings, and many complex statements do need to describe their relationships.
<select id= "selectusers" resulttype= "Map" >
Select ID, username, hashedpassword
From some_table
WHERE id = #{id}
</select>
Such a statement simply acts on all columns that are automatically mapped to the HASHMAP key, which is specified by the Resulttype property. This is useful in many cases, but
HashMap cannot describe a domain model well. That way your application will use JavaBeans or POJOs (Plain old Java Objects, plain Java objects) as the domain model. MyBatis is supportive of both. Take a look at the following JavaBean:
Based on the JavaBean specification, the above class has 3 properties: Id,username and Hashedpassword. These are exactly matched to the column name in the SELECT statement.
Such a JavaBean can be mapped to a result set, as simple as mapping to HASHMAP.
<select id= "Selectusers" resulttype= "Com.someapp.model.User" >
Select ID, username, hashedpassword
From some_table
WHERE id = #{id}
</select>
Remember that the type alias is your partner. You can use them without entering the full path of the class. Like what:
<!--in Mybatis-config.xml file---
<typealias type= "Com.someapp.model.User" alias= "User"/>
<!--in SQL Mapping XML file---
<select id= "Selectusers" resulttype= "User" >
Select ID, username, hashedpassword
From some_table
WHERE id = #{id}
</select>
To resolve a list in MySQL that is inconsistent with Java properties The second method:
Resultmap the best places you've learned a lot, but you haven't really seen one yet. These simple examples don't need much more than you see.
In these cases, MyBatis automatically creates a resultmap behind the scenes, mapping columns to JavaBean properties based on the property name. If the column name does not match exactly, you can
Use the alias of the SELECT clause (a basic SQL attribute) on the column name to match the label. Like what:
Just out
For the reasons of the example, let's take a look at what the external resultmap in the last example looks like, and this is another way to resolve the column name mismatch.
<resultmap id= "Userresultmap" type= "User" >
<id property= "id" column= "user_id"/>
<result property= "username" column= "username"/>
<result property= "password" column= "password"/>
</resultMap>
Advanced Result Mapping:
<!--Very Complex Result Map--
<resultmap id= "Detailedblogresultmap" type= "Blog" >
<constructor>
<idarg column= "blog_id" javatype= "int"/>
</constructor>
<result property= "title" column= "Blog_title"/>
<association property= "Author" 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" javatype= "Author"/>
<collection property= "Comments" oftype= "Comment" >
<id property= "id" column= "comment_id"/>
</collection>
<collection property= "tags" oftype= "Tag" >
Your Visitors can save Your Web pages as PDF in one click with http://pdfmyurl.com!
<id property= "id" column= "tag_id"/>
</collection>
<discriminator javatype= "int" column= "Draft" >
<case value= "1" resulttype= "Draftpost"/>
</discriminator>
</collection>
</resultMap>
Constructor: When a class is instantiated, it is used to inject results into the constructor method
Idarg:id parameters; Marking results as IDs can help improve overall performance
Arg-A common result injected into the constructor method
ID: an ID result; Marking results as IDs can help improve overall performance
result– normal results injected into a field or JavaBean property
association– a complex type association; many results will be wrapped into this type
Embed result mapping – the association of the result map itself, or refer to a
collection– sets of complex types
Embed result mapping – the set of the result map itself, or refer to a
ID & Result:
The only difference between the two is that the result of the ID representation will be the identity attribute used when comparing the object instance. This helps to improve overall performance, especially caching and embedding result mappings
(that is, federated mapping).
JDBC Type:
MyBatis using Notes