配置
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
- configuration(配置)
- properties(属性)
- settings(设置)
- typeAliases(类型别名)
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器)
mybatis官方文档,配置这里。
属性(properties)
<?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 id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--配置一个时区-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://123.57.158.82/Mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=true&verifyServerCertificate=false"/>
<property name="username" value="****"/>
<property name="password" value="*******"/>
</dataSource>
</environment>
</environments>
<!--注册中心-->
<mappers>
<mapper resource="com/kyz/dao/UserMapper.xml"/>
</mappers>
</configuration>
这里的propert的配置是十分繁琐的,并且需要&;来进行转义,核心配置文件十分臃肿,现在初步优化。
我们在main resources目录下创建一个db.properties配置文件,在这内部给出driver、url、username和password对应的值,
driver=com.mysql.jdbc.Driver url=jdbc:mysql://123.57.158.82/Mybatis?useUnicode=true&characterEncoding=UTF-8&useSSL=true&verifyServerCertificate=false username=**** password=*******,
在核心配置文件响应的位置加入<properties resources="db.properties"></properties>,注意位置一定要放对,mybatis-config.xml文件内对各项属性的前后顺序有严格要求,不能像在web.xml中直接删掉
<web-app>直接完事儿。
现在核心文件变为了
<!--引入外部配置文件-->
<properties resource="db.properties"></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>
类型别名(typeAliases)
同样DAO中的UserMapper的配置信息也是十分臃肿的。
<select id="getUserListByInfo" resultType="com.kyz.pojo.UserInfo"> select * from Mybatis.user; </select>
这里需要把这个resultType属性给优化掉。
<!--配置类别名--> <typeAliases> <package name="com.kyz.pojo"/> </typeAliases>
在mybatis-config.xml中配置该属性可以去掉臃肿的重复包路径代码。
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。例如:
<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>
<typeAlias type="com.kyz.pojo.UserInfo" alias="userinfo"></typeAlias>