I. Introduction
This article covers a large number of mybatis configurations, read one, and earn lifetime.
Two properties configuration
In the previously published article, the configuration database connection information is directly written to mybatis-config.xml
; in order to be flexible and convenient to use, and dynamically modify the configuration, we extract the configuration content into a configuration file db.properties
(placed in the resource directory, which can also be customized), and then configure the file <properties>
label incorporated db.properties
location is located, then use $ {key} in the configuration file db.properties
corresponding to key value; modify the configuration file for this modified only outside after db.properties
the contents can;
2.1 mybatis-config.xml
The configuration file is modified as follows. After MyBatis 3.4.2, it also supports default attributes such as $ {username: root}. When the attribute is not defined in the configuration file, the default attribute root will be read. For more detailed attribute configuration, see the official website;
<!-- 引入resource目录下的配置文件 -->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
<!-- 全局环境配置-->
<environments default="development">
<environment id="development">
<!-- 事物 -->
<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>
复制代码
2.2 db.properties
The property file is as follows;
driver = com.mysql.jdbc.Driver
username = root
url = jdbc:mysql://192.168.0.100:3306/mybatis
password = 123456
复制代码
Three typeAliases configuration
typeAliases alias is the meaning of the results of our inquiry before has a resultType
property, each time have to use the fully qualified name of the class of return (for example: com.zszxz.config.entity.Student), this configuration more complicated, mybatis You can use a simple class name instead of the fully qualified name of the class by configuring an alias;
3.1 Configuration method one
The first configuration is complicated, that is, how many return type of entity classes you have, on the property mybatis-config.xml of <typeAliases>
how many class name mapping configuration;
The snippet of mybatis-config.xml code is as follows, and the placement of the labels should be noted ;
<typeAliases>
<typeAlias type="com.zszxz.config.entity.Student" alias="student"></typeAlias>
</typeAliases>
复制代码
The mapper.xml configuration is as follows:
<!-- 查询学生-->
<select id="getStudent" resultType="student">
select * from student
</select>
复制代码
3.2 Configuration method two
The second configuration method is to use the package name configuration, mybaits will automatically map, we can use the simple name of the class in mapper.xml to represent the full class name, this method is more concise, it is recommended to use;
Mybatis-config.xml code snippet is as follows
<typeAliases>
<package name="com.zszxz.config.entity"/>
</typeAliases>
复制代码
The mapper.xml configuration is as follows:
<!-- 查询学生-->
<select id="getStudent" resultType="student">
select * from student
</select>
复制代码
3.3 Configuration Mode 3
The third configuration method is to use annotation configuration. This configuration method is based on the second configuration method, which can modify the default alias (the default is to use the simple class name of the class); use the annotation @Alias on the return type entity to specify Alias
The entities are as follows:
/**
* @Author lsc
* @Description <p> </p>
* @Date 2019/12/1 20:07
*/
@Alias("stu")
public class Student {
// id
private String id;
// 学生姓名
private String name;
// 学生编号
private String number;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
复制代码
mapper.xml is as follows:
<!-- 查询学生-->
<select id="getStudent" resultType="stu">
select * from student
</select>
复制代码
3.4 Mybatis built-in alias
Mybatis has built-in multiple alias types, that is, some data types can use simple names of classes without configuring aliases, such as the basic data types and corresponding packaging types, collections, iterators, String classes, large values, dates, etc. ;
Four setting configuration instructions
Seetting configuration instructions are as follows
Attributes | Explanation | Defaults |
---|---|---|
cacheEnabled | Turn on global cache | false |
lazyLoadingEnabled | Global lazy loading, all associated objects will be lazy loaded; specific associations can be configured using the fetchType attribute | false |
aggressiveLazyLoading | After opening, no matter what method is called to load the object, all properties of the object will be loaded, otherwise it will be loaded on demand | false |
multipleResultSetsEnabled | Whether to allow a single statement to return multiple result sets (requires driver support) | teue |
useColumnLabel | Use column labels instead of column names | false |
useGeneratedKeys | Allow JDBC to support automatic generation of primary keys, driver support is required | false |
autoMappingBehavior | MyBatis automatically maps columns to fields or attributes; NONE means to cancel automatic mapping; PARTIAL will only automatically map result sets that do not define result set mapping. FULL will automatically map any complex result set; | PARTIAL |
autoMappingUnknownColumnBehavior | Notify the behavior of automatically mapping the target unknown column (or unknown attribute type) NONE ;: No response;: WARNING Output reminder log FAILING ;: Mapping failure thrown SqlSessionException ; |
NONE |
defaultExecutorType | Set the default actuator. SIMPLE is an ordinary executor; REUSE executor will reuse prepared statements (prepared statements); BATCH executor will reuse statements and perform batch updates | SIMPLE |
defaultStatementTimeout | Set the timeout period and determine the number of seconds the driver waits for a database response | no |
defaultFetchSize | Set a hint value for the number of fetched results (fetchSize); | no |
safeRowBoundsEnabled | Allow pagination (RowBounds) in nested statements; set to false if allowed | false |
safeResultHandlerEnabled | Allow paging (ResultHandler) in nested statements; set to false if allowed | false |
mapUnderscoreToCamelCase | Whether to enable automatic hump naming rules | false |
localCacheScope | MyBatis uses Local Cache to prevent circular references and accelerate repeated nested queries. SESSION will cache all queries executed in a session; STATEMENT local session is only used for statement execution, different calls to the same SqlSession will not share data | SESSION |
jdbcTypeForNull | When no specific JDBC type is provided for the parameter, specify the JDBC type for the null value | OTHER |
lazyLoadTriggerMethods | Specify which object's method triggers a lazy load | equals,clone,hashCode,toString |
defaultScriptingLanguage | Specify the default language for dynamic SQL generation. | org.apache.ibatis.scripting.xmltags.XMLLanguageDriver |
defaultEnumTypeHandler | 指定 Enum 使用的默认 TypeHandler |
org.apache.ibatis.type.EnumTypeHandler |
callSettersOnNulls | 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,依赖于 Map.keySet() 或 null 值初始化的时候比较有用。 | false |
returnInstanceForEmptyRow | 当返回行的所有列都是空时,MyBatis默认返回 null 。 当开启这个设置时,MyBatis会返回一个空实例;(新增于 3.4.2) |
false |
logPrefix | 指定 MyBatis 增加到日志名称的前缀 | unset |
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找 | unset |
proxyFactory | 代理工厂。指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。 | JAVASSIST (MyBatis 3.3 以上) |
vfsImpl | 指定 VFS 的实现 | unset |
useActualParamName | 使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1) |
true |
configurationFactory | 指定一个提供 Configuration 实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含一个签名为static Configuration getConfiguration() 的方法。(新增于 3.2.3) |
unset |
官方完整示例如下,实际开发中并非如此配置,按需配置;
<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="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
复制代码
五 typeHandlers 类型处理器
类型处理器故名思意,也就是可以在java类型和数据库jdbc类型之间转换;如果要自定义类型处理器就需要编写类型处理器类,然后在配置文件中配置,在SQL映射文件mapper.xml中使用。
5.1 自定义TypeHandle
本次示例就以字符串类型演示,需要继承BaseTypeHandler类,重写里面的方法,具体的代码清单如下,使用注解 @MappedJdbcTypes 会覆盖 泛型的String类型;
/**
* @Author lsc
* <p> 知识追寻者,字符串类型处理器</p>
*/
// 指定关联jdbc会改变泛型指定
//@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringTypeHandler extends BaseTypeHandler<String> {
public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
// 指定java参数类型(String)对应数据库类型(varchar)
preparedStatement.setString(i,s);
}
public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
return resultSet.getString(s);
}
public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
return resultSet.getString(i);
}
public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
return callableStatement.getString(i);
}
}
复制代码
5.2 mybatis-config.xml
在 mybaits的配置文件中配置自定义的类型处理器
<!--配置类型处理器,会覆盖默认的类型处理器 -->
<typeHandlers>
<typeHandler handler="com.zszxz.config.handler.StringTypeHandler"></typeHandler>
</typeHandlers>
复制代码
也可以使用包名全局扫描,减轻配置过程;
<!--配置类型处理器,会覆盖默认的类型处理器 -->
<typeHandlers>
<package name="com.zszxz.config.handler"/>
</typeHandlers>
复制代码
如果配置了jdbc的映射属性会覆盖泛型指定类型
<typeHandlers>
<!--指定关联jdbc会改变泛型指定 -->
<typeHandler handler="com.zszxz.config.handler.StringTypeHandler" javaType="java.lang.String" jdbcType="VARCHAR"></typeHandler>
</typeHandlers>
复制代码
5.3 SQL映射文件
使用 jdbcType=VARCHAR,javaType=String 指定类型转换;
<insert id="addStudent" parameterType="stu">
insert into student(`name`,`number`)
values (#{name,jdbcType=VARCHAR,javaType=String},#{number})
</insert>
复制代码
六 mappers映射器
mappers映射器就是配置引入SQL映射文件,也很简单,这边就给出官方示例,不再具体试验,有四种方式,通常我们掌握一至两种就足够日常开发使用;
6.1 相对于类路径方式
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
复制代码
6.2 资源绝对路径方式
<mappers>
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
<mapper url="file:///var/mappers/BlogMapper.xml"/>
<mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
复制代码
6.3 接口实现类的完全限定类名方式
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
复制代码
6.4 接口实现类的包名方式
<mappers>
<package name="org.mybatis.builder"/>
</mappers>
复制代码