问题描述:
当我们使用 maven 搭建 MyBatis 时,maven 在程序运行进行编译时,如果 mybati 使用外部配置文件,会发生 url 替换错误的现象
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.sql.SQLException: No suitable driver found for http://www.example.com
### The error may exist in UserMapper.xml
### The error may involve cn.hbh.dao.UserDaoIml.getUserList
### The error occurred while executing a query
### Cause: java.sql.SQLException: No suitable driver found for http://www.example.com
外部配置文件如下:
driver=com.mysql.cj.jdbc.Driver | |
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&serverTimezone=UTC | |
username=root | |
password=dkx |
Mapper.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 resource="druid.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/dkx/mybatis/dao/UserDaoMapper.xml"/> | |
</mappers> | |
</configuration> |
此时去看下 maven 编译程序后的文件,发现 maven 将外部配置文件的参数替换成 http://www.eample.com
将外部配置文件的 url 改为 jdbcUrl
properties 配置文件如下:
driver=com.mysql.cj.jdbc.Driver | |
jdbcUrl=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&serverTimezone=UTC | |
username=root | |
password=dkx |
mapper.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 resource="druid.properties"/> | |
<environments default="development"> | |
<environment id="development"> | |
<transactionManager type="JDBC"/> | |
<dataSource type="POOLED"> | |
<property name="driver" value="${driver}"/> | |
<property name="url" value="${jdbcUrl}"/> | |
<property name="username" value="${username}"/> | |
<property name="password" value="${password}"/> | |
</dataSource> | |
</environment> | |
</environments> | |
<!-- 每一个 Mapper.XML 都需要在 MyBatis 核心配置文件中注册!--> | |
<mappers> | |
<mapper resource="com/dkx/mybatis/dao/UserDaoMapper.xml"/> | |
</mappers> | |
</configuration> |
再次运行