MyBatis
MyBatis is an open source project Apache iBatis, iBatis The word comes from the "internet" combination and "abatis", is a Java-based persistence framework. IBatis persistence framework include SQL Maps and Data Access Objects (DAO)
Mybatis is a semi-automatic ORM (Object Relation Mapping) framework
sql and java coding separate functional boundaries clear, a focus on business, a focus on data
MyBatis Global Configuration
MyBatis global configuration file structure predetermined order is good, but not an upside down position may be omitted
1) properties property
May be arranged in a typical Java file attributes, sub-elements can also be configured by the properties element
You can also create a resource file, import external files by properties
resource: introducing attribute file from the classpath
url: the introduction of the network path or file attributes disk path
<properties> <property name="driver" value="com.mysql.jdbc.Driver" /> </properties> <!-- 引入类路径下文件 --> <properties resource="db.properties"></properties>
It is extremely important to adjust the settings MyBatis, they will change the runtime behavior of MyBatis
< Settings > <-! Mapped to underline camelCase -> < Setting name = "mapUnderscoreToCamelCase" value = "to true" /> <-! Set Mybatis default null value to the process -> < Setting name = "jdbcTypeForNull " value =" NULL " /> <-! opening delay loading -> < setting name =" lazyLoadingEnabled " value =" to true " /> <-! data set is loaded on demand or all -> < setting name = "aggressiveLazyLoading" value="false"/> <! - Configure secondary cache Open -> < Setting name = "cacheEnabled" value = "to true" /> </ Settings >
3) typeAliases alias processing
Type an alias for Java type is set a short name, we can easily refer to a class elsewhere in the configuration file.
In many cases, you can create an alias batch set a default alias for each class in this package is a simple class name in lowercase form
<typeAliases> <package name="com.mybatis.bean"/> </typeAliases>
MyBatis has taken good alias
4) typeHandlers type processor
Whether the value is a parameter set MyBatis prepared statement (the PreparedStatement) in the concentrator or retrieves a value from the results, are acquired with the type of the Java type of processor suitable manner
MyBatis3.4 Previous versions required us to manually register these processors, later versions are automatically registered , so the basic need to set
We can also rewrite the type of processor or create your own to deal with the type of processor does not support or non-standard type
- Org.apache.ibatis.type.TypeHandler implement interfaces or extend org.apache.ibatis.type.BaseTypeHandler
- JDBC type which specifies a map (optional)
- Sign in mybatis global configuration file
5) objectFactory object factory
6) plugins plugin mechanism
We can modify the behavior of some of the core MyBatis through plug-ins. One way to perform any plug-ins through the dynamic proxy mechanism, can intervene four objects
<plugins> <!-- 分页插件 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins>
Four Objects
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed) ParameterHandler (getParameterObject, setParameters) ResultSetHandler (handleResultSets, handleOutputParameters) StatementHandler (prepare, parameterize, batch, update, query)
7) environments environment configuration
MyBatis can be configured to a variety of environments, use of a tag environment according to the requirements of each environment to configure and assign a unique identifier
You can specify an environment through environments tag default attribute identifier fast switching environment
id: Specifies the current environment of unique identification transactionManager, and must have dataSource
<environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments>
The actual development we use Spring to manage data sources, and transaction control configurations to cover the configuration
8) databaseIdProvider database vendor identification
MyBatis can execute different statements based on different database vendors
<databaseIdProvider type="DB_VENDOR"> <property name="MySQL" value="mysql"/> </databaseIdProvider>
Type: DB_VENDOR, using MyBatis provided VendorDatabaseIdProvider analytic database vendor identification. You can also customize the interface to achieve DatabaseIdProvider.
After configuring databaseIdProvider, additions and deletions in the SQL mapping file change search tag within the specified database to identify databaseId alias
<select id="getEmployeeById" resultType="com.mybatis.bean.Employee" databaseId="mysql"> select * from tbl_employee where id = #{id} </select>
MyBatis matching rules are as follows
① If no databaseIdProvider label, then databaseId = null
② If the configuration name databaseIdProvider tag, using the tag to match the database configuration information, configuration settings databaseId on match = specified value, or still is null
③ If databaseId is not null, he would find sql statement configuration of databaseId
④ MyBatis will load without databaseId properties with all the statements and match the current database databaseId property. If both find databaseId and the same statement with and without databaseId, the latter will be discarded.
9) mappers mapper
When mybatis for initialization, told mybatis Mapper mapping file which need to be introduced
Introducing classpath file: resource
url: the introduction of the network path or file in the disk path
class: introduction Mapper Interface
Use bulk registration Often, this approach requires SQL mapping file name must be the same as the interface name and in the same directory
<mappers> <package name="com.mybatis.dao"/> </mappers>
mapper mapping file
The real power lies in its MyBatis mapping statement, is to build for the SQL statement
<mapper namespace="main.mapper.BookMapper" > </mapper>
SQL mapping files have only a few top-level elements
cache - given namespace cache configuration.
cache-ref - references to other namespaces cache configuration.
resultMap - is the most complex and powerful element that describes how to load from the database result object.
parameterMap - obsolete! Old-style parameter mapping. Inline parameters are preferred , this element may be removed in the future, there will not be recorded.
sql - reusable statement block can be referenced by other statements.
insert - Mapping insert statements
update - mapped UPDATE statement.
delete - Mapping delete statement
select - mapping query language
MyBatis default is not automatically submitted, the need to manually submit:. SQLSESSION the commit ();
insert
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id"> INSERT INTO users (id,username,PASSWORD) VALUES(NULL,#{username},#{password}) </insert>
delete
<delete id="deleteUser"> DELETE FROM users WHERE id = #{id} </delete>
update
<update id="updateUser"> UPDATE users SET name=#{name},email=#{email} WHERE id = #{id} </update>
select
<select id="getUserById" resultType="main.beans.User"> SELECT id,username,`password`,`name`,email FROM users WHERE id = #{id} </select>
Acquired primary key generation and
Support database is divided into primary keys increment and does not support, mysql is supported
Function: when inserting a new data can immediately query by its primary key id value of this data is generally provided in the insert in useGeneratedKeys is true, return to the main key id database automatically generated, KeyColumn primary key specified database table is, the keyProperty with member variables to specify the incoming object.
Note: settings are provided as global, mapper interface (Note) useGeneratedKeys set parameter value will override the settings in global settings useGeneratedKeys element parameter value, the parameter useGeneratedKeys xml mapper configured only affect mapper xml
@Options(useGeneratedKeys=true,keyProperty="userId",keyColumn="userId")
Parameter passing
1) a single parameter common type
Acceptable basic type, packing type, a string type. MyBatis this case this parameter can be used directly, # {abc}, braces can be readily defined
2) a plurality of parameters
Any number of parameters, will be repackaged into a Map MyBatis passed. Map key is param1, param2, or 0,1 ..., # {param1, param2}
Value is the value of the parameter # {key1, key2}: Get value of the parameter, the pre-compiled SQL. Safety.
3) named parameters
For the parameters used @Param a name, MyBatis will set up those parameters encapsulated in the map, key is our own designated name
public Employee getEmployeeById(@Param("id")Integer id);
4) POJO
resultType automatically mapped when these parameters are part of our business POJO, we passed directly POJO
autoMappingBehavior default is PARTIAL, enable automatic mapping. The only requirement is the result of a consistent set of attribute names and column names javaBean
5) Map
We can also be packaged as a plurality of parameter map, # {key} is directly transmitted directly into the key value in the map
1) single-line data query returns a collection Map
public Map<String,Object> getEmployeeByIdReturnMap(Integer id );
2) query returns multiple rows of data collection Map
@MapKey ( "the above mentioned id") // specify which properties using the object to act as a map of Key public the Map <Integer, the Employee> getAllEmpsReturnMap ();
6) Collection/Array
MyBatis will be encapsulated into a map incoming, Collection corresponding key is a collection, Array corresponding to the key is the array. If the determination is set List, key may also be a list.
resultMap custom mapping
Custom resultMap, you can map the result set of advanced
1) id: completion of primary key for mapping
2) result: the column used to complete the normal map
the above mentioned id, the Result property
<resultMap id="getBookById" type="main.beans.User"> <id column="id" property="id"></id> <result column="username" property="username"></result> <result column="password" property="password"></result> </resultMap>
. 3) Association : a complex type association, when an attribute of an object is an object, typically by wrapping the result of this type
We can use the joint inquiry, and by way of cascade attribute package objects. Encapsulation rules define an object using the association's label
<select id="getEmployeeAndDept" resultMap="myEmpAndDept" > SELECT e.id eid, e.last_name, e.email,e.gender ,d.id did, d.dept_name FROM tbl_employee e , tbl_dept d WHERE e.d_id = d.id AND e.id = #{id} </select> <resultMap type="com.mybatis.beans.Employee" id="myEmpAndDept"> <id column="eid" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> <!-- 级联的方式 --> <result column="did" property="dept.id"/> <result column="dept_name" property="dept.departmentName"/> </resultMap>
Should have specific CRUD methods for each entity class, which is the DAO layer, so we can use the association step inquiry
On the basis of the inquiry step by step, you can use lazy loading to improve the efficiency of queries, only in the global Settings Configuration
<select id="getEmployeeAndDeptStep" resultMap="myEmpAndDeptStep"> select id, last_name, email,gender,d_id from tbl_employee where id =#{id} </select> <resultMap type="com.mybatis.beans.Employee" id="myEmpAndDeptStep"> <id column="id" property="id" /> <result column="last_name" property="lastName"/> <result column="email" property="email"/> < Result column = "Gender" Property = "Gender" /> < Association Property = "Dept" SELECT = "com.mybatis.dao.DepartmentMapper.getDeptById" // query method defined in the package mapper full class name column = "D_ID " fetchType =" eager " > </ Association > </ The resultMap >
. 4) Collection : complex types, when an attribute of an object is a collection object
We can use the joint inquiry, and by way of cascade attribute package objects. Encapsulation rules define an object using a collection of labels
property: property name associated
Set of types of elements: ofType
The actual development often can complete the query by a stepwise manner.
<select id="getDeptAndEmpsByIdStep" resultMap="myDeptAndEmpsStep"> select id ,dept_name from tbl_dept where id = #{id} </select> <resultMap type="com.mybatis.beans.Department" id="myDeptAndEmpsStep"> <id column="id" property="id"/> <result column="dept_name" property="departmentName"/> <collection property="emps" select= "com.mybatis.dao.EmployeeMapper.getEmpsByDid" // query method defined in the package mapper full class name column = "ID" > </ Collection > </ The resultMap >
Multi-step query column values passed
If the query step, to be passed to query a plurality of call parameters, then the parameters need to be packaged into a plurality Map to be passed, the following syntax: {k1 = v1, k2 = v2 ....}
When a query method called values, we must refer to the value of the Map mode, when the need for strict accordance with the key used to map the package value.
fetchType property
<Association> and <collection> tag can be set fetchType, specify whether you want to use this query delay loaded. The default is fetchType = "lazy", if this inquiry do not want to use lazy loading, you can set fetchType = "eager".