在 纯MyBatis测试(不加载Spring) 的方案4中,mybatis-config.xml 是 MyBatis 的核心配置文件,需要你手动创建并放置在项目的资源目录中。以下是具体说明:
- 文件位置
将 mybatis-config.xml 放在项目的 资源目录 下:
powershell
src/test/resources/mybatis-config.xml
- 配置文件内容示例
powershell
<?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>
<!-- 全局设置 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 配置数据源(需替换为你的数据库信息) -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/你的数据库名?useSSL=false"/>
<property name="username" value="用户名"/>
<property name="password" value="密码"/>
</dataSource>
</environment>
</environments>
<!-- 指定Mapper接口所在的包 -->
<mappers>
<package name="com.zykj.moon.order.mapper"/>
</mappers>
</configuration>
- 需要同步修改的测试代码
java
public class PureMyBatisTest {
private static SqlSessionFactory sqlSessionFactory;
private static PaidGoodsDurationMapper mapper;
@BeforeAll
static void setup() throws Exception {
// 加载MyBatis配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 获取Mapper实例
mapper = sqlSessionFactory.openSession().getMapper(PaidGoodsDurationMapper.class);
}
@Test
void testSelect() {
PaidGoodsDuration result = mapper.selectExistDuration(9696665, 27L, 1);
assertNotNull(result);
}
}
- 关键注意事项
数据库驱动依赖
确保 pom.xml 中包含数据库驱动:
xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
<scope>test</scope>
</dependency>
Mapper接口位置
xml
<mappers>
<!-- 方式1:扫描包 -->
<package name="com.zykj.moon.order.mapper"/>
<!-- 方式2:指定具体Mapper XML文件 -->
<mapper resource="mapper/PaidGoodsDurationMapper.xml"/>
</mappers>
日志输出(可选)
在 mybatis-config.xml 中添加日志配置:
xml
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
- 替代方案(无需XML)
如果不想用XML配置,可以用Java代码直接构建:
java
@BeforeAll
static void setup() {
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("123456");
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("dev", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(PaidGoodsDurationMapper.class);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
总结
方案 | 优点 | 缺点 |
---|---|---|
XML配置 | 配置集中,易于维护 | 需要额外文件 |
Java代码配置 | 灵活,无需XML | 硬编码,修改需重新编译 |
选择哪种方式取决于项目需求。对于简单测试,Java代码配置更直接;对于复杂项目,XML配置更规范。