MyBatis configuration in detail (b)

MyBatis configuration in detail (b)

img

  1. Global MybatisConfig

1. Configure content and order

MybatisConfig.xml is Mybatis global configuration file, configuration content and order thereof is as follows:

1: properties (attributes)

2: settings (global parameters)

3: typeAliases (type alias)

4: typeHandlers (processor type)

5: objectFactory (Object Factory)

6: plugins (plugin)

7: environments (environmental objects collection property)

8: environment (sub-attribute Object Environment)

9: transactionManager (Transaction Management)

10: dataSource (data source)

11: mappers (mapper)

1.1. Properties (attributes)

  • properties properties

You can load the database configuration information. Db.properties created in src / main / resources in

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

Db.properties loaded in the MybatisConfig.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> 
    <!-- 读取数据库配置信息 --> 
    <properties resource="db.properties"></properties> 
    <environments default="development"> 
        <environment id="development"> 
            <transactionManager type="JDBC" /> 
            <dataSource type="POOLED"> 
                <property name="driver" value="${jdbc.driver}" /> 
                <property name="url" value="${jdbc.url}" /> 
                <property name="username" value="${jdbc.username}" /> 
                <property name="password" value="${jdbc.password}" /> 
            </dataSource> 
        </environment> 
    </environments>
</configuration>
  • by mappers (mapper)

mappers map file for loading into the global configuration file, Mybatis there are four ways to load the mapping file. This is another resource, url, class, package. Reference configuration is as follows:

<mappers>
    <mapper resource="userInfoMapper.xml" />
    <mapper url="file:///D:\mybatis-1\config\userInfoMapper.xml" />
    <mapper class="cn.it.mapper.IUsersMapper"/>
    <package name="cn.it.mapper"/>
</mappers>

resource

Use of resources with respect to the path of the class, such as:

<mapper resource="userInfoMapper.xml" />

This method is time you load a map file.

url

Using fully qualified path, such as:

<mapper url="file:///D:\mybatis-1\config\userInfoMapper.xml" />

This method is time you load a map file. Due to the use of absolute path, using this method is not recommended.

class

Use mapper interface path, such as

<mapper class="cn.itlaobing.mybatis.mapper.IUserInfoMapper"/>

Note: This method requires mapper and mapper interface name mapping file with the same name and in the same directory.

package

Registration packets specified under all mapper interface, such as:

<package name="cn.itlaobing.mybatis.mapper"/>

Note: This method requires the mapper and mapper interface name mapping file with the same name and in the same directory. This way you can achieve bulk load, is recommended.

2. Enter the map parameterType

ParameterType input map is set by the attribute Mapper Statement. All input mapping is required to complete the following two steps:

  1. Mapper mapping configuration
  2. Mapper interface definition

Mybatis input mapping is to map Java objects to SQL statements in the column values. Input mapping Mybatis forms include simple type input mapping, POJO type input mapping, VO type input mapping, HashMap input mapping.

  • Simple type input mapping

Requirements: id specified by the user queries

  1. Mapper mapping configuration
<select id="findUserInfoById" parameterType="int" resultType="cn.it.model.UsersModel"> 		select * from userInfo where userid=#{userid}
</select>
  1. Mapper interface definition
public UsersModel findUsersById(int userid)
  • POJO type input mapping

Requirements: Add User

  1. Mapper mapping configuration
<insert id="insertUsers" parameterType="cn.it.model.UsersModel"> 
    <selectKey keyProperty="userid" order="AFTER" resultType="java.lang.Integer"> 
        select last_insert_id()
    </selectKey> 
    insert into users(username,password,createtime) values(#{username},#{password},#{createtime});
</insert>
  1. Mapper interface definition
public void insertUsers(UsersModel model);
  • HashMap type input mapping

Requirements: According to user queries the user name and gender

  1. Mapper mapping configuration
<select id="findByHashMap" parameterType="hashmap" resultType="cn.it.model.UsersModel"> 	SELECT * FROM users WHERE username =#{username} AND password=#{password}
</select>
  1. Mapper interface definition
public List<UsersModel>  findByHashMap(HashMap<String, String> hashMap) ;

3. Output Mapping resultType

ResultType input map is set by the attribute Mapper Statement. All of the output mappings should complete the following two steps:

  1. Mapper mapping configuration
  2. Mapper interface definition

Mybatis output mapping is the result of the query is mapped to Java objects. Mybatis may be a single data query (e.g., aggregate queries) mapped to the simple type of Java, will inquire POJO mapped to a single record object, a plurality of queries to a set of mapped records.

If the query is a single record, Mybatis call selectOne () method, and the results are mapped to POJO objects. If the query multiple records, Mybatis call selectList () method, and the results are mapped to a collection of POJO. Mybatis call between selectOne () or selectList is () return a value determined according to the method Mapper interface, if the type of the return value is set, the call selectList is () method, if the return value is POJO object, call between selectOne () method.

  • Simple type output mapping

Record number of queries userInfo table: demand

  1. Mapper mapping configuration
<select id="findUsersCount" resultType="int">    
    select count(1) from userInfo
</select>
  1. Mapper interface definition

public int findUsersCount ();

  • POJO objects output mapping

Requirements: According id specified user query, in this case with findUserInfoById.

  1. Mapper mapping configuration
<select id="findUsersById" parameterType="int"    resultType="cn.it.model.UsersModel">    	select * from users where userid=#{userid}
</select>
  1. Mapper interface definition
public UsersModel findUsersById(int id);
  • HashMap type output mapping

Requirements: query for all users.

  1. Mapper mapping configuration
<select id="findToHashMap" resultType="hashmap">
    select * from users
</select>
  1. Mapper interface definition
public List<Map<String, String>> findToHashMap() throws Exception;

4. Dynamic sql

img

Enter your user name, user's gender and order number

select * from userInfos where username=#{username} 
and gender=#{gender}and id 
in(select userId from userorders where orderid=#{orderId})

Like this many conditions, wherein the portion where clause requires dynamic mosaic filter criteria selected by the user. Mybatis provides dynamic SQL, Dynamic SQL refers to dynamic SQL statements by splicing a variety of labels Mybatis provided.

  1. Mapper mapping configuration
<!-- 动态SQL-多条件查询 -->
<select id="findUsersCondition" parameterType="hashmap"resultType="cn.it.model.UsersModel">
    select * from users     
    <!-- where标签自动去掉满足条件的第一个and -->     
    <where>         
        <!-- 如果userName不为空,则将userName拼接到查询条件中 -->         
        <if test="username!=null">
            and userName=#{username}         
        </if>         
        <!-- 如果gender不为空,则将gender拼接到查询条件中 --> 
        <if test="password!=null">          
            and password=#{password}     
        </if>     
        <!-- 如果orderId不为空,则将orderId拼接到查询条件中 -->   
        <if test="orderId!=null">     
            and id in(select userId from orders where id=#{orderId})  
        </if> 
    </where>
</select> 
  1. Mapper interface definition
public List<UserInfosModel> findUserInfosCondition(HashMap<String, String> condition);

5. lazy loading

We need to query related information, use Mybatis lazy loading feature can effectively reduce the pressure of the database, only the first query main query table information, information associating table reloading when user gets.

association and many of the collection Mybatis one association can be achieved lazy loading. To use resultMap when lazy loading can not be used resultType.

  1. Start lazy loading

Mybatis default is not open lazy loading configuration, you need to configure settings in SqlMapperConfig.xml by lazyLoadingEnabled in, aggressiveLazyLoading to turn on lazy loading.

<settings>
    <setting name="lazyLoadingEnabled" value="true"/> 
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>

6. Cache

  1. Why use caching

As a cache (also referred to as cache) it is for subtracting the pressure on the database to improve the performance of the database. Cache implementation principle is not to destroy the query from the database objects in after use, but in the memory (cache), when once again need to get the object directly available directly from memory (cache) is stored, no longer to database implementation of the select statement, thereby reducing the number of database queries, thus improving the performance of the database. Map caching is to use a set of cached data.

Mybatis has a cache and secondary cache. Level cache scope is the same SqlSession, sql execute the same statement twice in the same sqlSession, the data for the first time will be finished in a database query written cache (memory), and the second will get the data from the cache will no longer from a database query to improve query efficiency. When the end of a sqlSession the sqlSession in the cache would not exist. Mybatis cache is enabled by default.

SqlSession secondary cache is shared by a plurality, which scope is the same namespace Mapper, different sqlSession performed twice under the same namespace sql statement and transferred to the same parameters in sql i.e., perform the same final sql statement, first data will be finished once the database query written to the cache (memory), the second gets the data from the cache will not be from a database query to improve query efficiency. Mybatis not enabled by default open the two secondary cache needs to be configured in setting the global cache parameters.

  • Introduction cache

A cache area is divided in a unit according SqlSession. Each query cache region will start to find, if not found from the database query, write caching database query after the data.

Mybatis internal memory cache using a cache HashMap data, key to hashCode + sqlId + Sql statement. value to a query from the map generated java object.

  • Introduce the principle of secondary cache

The secondary cache area is divided mapper namespace, the data mapper queries the same namespace cache in the same area, if a namespace for each mapper mapper proxy method is different, as will be understood at this time is a secondary cache area mapper division.

Each query cache region will start to find, if not found from the database query, and the query to the data written to the cache. Mybatis internal storage cache uses a HashMap, key to hashCode + sqlId + Sql statement. value to a query from the map generated java object.

  • Configure two cache configuration

The first step: Turn on the secondary cache

SqlMapperConfig.xml enable the secondary cache, as shown in the following code, the secondary cache is disabled when the setting is enabled cacheEnabled secondary cache is true, set to false.

<setting name="cacheEnabled" value="true"/>

Step two: POJO serialization

POJO class implements all the serial interfaces Java.io. Serializable.

The third step: configuration mapping file

Start with the area to find the cache, if no query from the database and query the data written to the cache. Mybatis internal storage cache uses a HashMap, key to hashCode + sqlId + Sql statement. value to a query from the map generated java object.

  • Configure two cache configuration

The first step: Turn on the secondary cache

SqlMapperConfig.xml enable the secondary cache, as shown in the following code, the secondary cache is disabled when the setting is enabled cacheEnabled secondary cache is true, set to false.

<setting name="cacheEnabled" value="true"/>

Step two: POJO serialization

POJO class implements all the serial interfaces Java.io. Serializable.

The third step: configuration mapping file

In Mapper mapping file is added, it means mapper open L2 cache.

Published 10 original articles · won praise 3 · views 65

Guess you like

Origin blog.csdn.net/weixin_42174239/article/details/104524551