配置文件之基本优化
# 配置文件之基本优化🎋
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下:
- configuration(配置)
- properties(属性) (opens new window)
- settings(设置) (opens new window)
- typeAliases(类型别名) (opens new window)
- typeHandlers(类型处理器) (opens new window)
- objectFactory(对象工厂) (opens new window)
- plugins(插件) (opens new window)
- environments(环境配置)
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseIdProvider(数据库厂商标识) (opens new window)
- mappers(映射器) (opens new window)
# 1、mybatis-config.xml配置文件属性优化
mybatis-config.xml
中拥有数据库的账号密码,安全起见,不能直接加入到编译文件中,新建一个db.properties
,将驱动、URL、账号、密码等数据存储到这里,然后在mybatis-config.xml
调用即可。
<!--加载properties文件到MyBatis配置文件中-->
<properties resource="db.properties"></properties>
1
2
2
【示例】:mybatis-config.xml
<?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>
<!--加载properties文件到MyBatis配置文件中-->
<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>
<!--每一个mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers>
<mapper resource="com/singerw/mapper/UserMapper.xml"/>
<mapper resource="com/singerw/mapper/ArticleMapper.xml"/>
</mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
【示例】:db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/goku?serverTimezone=Asia/Shanghai
username=root
password=795200
1
2
3
4
2
3
4
# 2、 类型别名优化
在Mapper XML中使用实体类时候,每一次都需要从com.singerw.pojo.XXX中加载拿取使用,例如resultType="Article"的等等,为方便起见,直接在取别名在mybatis-config.xml文件中给该实体类取别名,方便使用,也有其他的作用。
# 🅰️方案一、DIY别名
【示例】mybatis-config.xml
<!-- 别名 -->
<typeAliases>
<typeAlias type="com.singerw.pojo.User" alias="User" />
<typeAlias type="com.singerw.pojo.Article" alias="Article" />
</typeAliases>
1
2
3
4
5
2
3
4
5
【示例】基本使用
<mapper namespace="com.singerw.mapper.ArticleMapper">
<!--查询所有文章-->
<select id="getArtilceList" resultType="Article">
select *
from artilce;
</select>
</mapper>
1
2
3
4
5
6
7
2
3
4
5
6
7
# 🅱️方案二、扫描包别名
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
<typeAliases>
<package name="com.singerw.pojo"/>
</typeAliases>
1
2
3
2
3
会扫描实体类的包,它的默认别名就为这个类的类名,首字母小写!
- 实体类比较少的时候建议使用第一种。
- 实体类比较多的时候建议使用第二种。
编辑 (opens new window)