平时都是集成在框架里使用的,单元测试的时候需要从文件维护些数据到数据库,就写了下独立使用的代码
MybatisTest.java
package com.seer.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class MybatisTest {
@Test
public void run() throws IOException {
InputStream inputStream = new FileInputStream(new File("D:\\Code\\oilCard\\src\\test\\java\\com\\sdgs\\mob\\mybatis\\mybatis-config.xml"));
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Mapper mapper = sqlSession.getMapper(Mapper.class);
int count = mapper.test();
System.out.println(count);
}
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="false"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="true"/>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
<!-- <setting name="useGeneratedKeys" value="true" /> -->
<!-- 使用列别名替换列名 默认:true -->
<!-- <setting name="useColumnLabel" value="true" /> -->
<!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true" /> -->
</settings>
<environments default="test">
<environment id="test">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="username" value="用户名"/>
<property name="password" value="密码"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载mapper文件,直接加载class -->
<mapper class="com.seer.mybatis.Mapper"/>
</mappers>
</configuration>
Mapper.java
package com.seer.mybatis;
import org.apache.ibatis.annotations.Select;
interface Mapper {
// 注解sql,复杂的实现百度下
@Select("select count(1) from sys_province")
int test();
}