测试类
private static SqlSession sqlSession = null;
private static RunoobTblMapper mapper;
@BeforeClass
public static void setUpMybatisDatabase() throws IOException {
InputStream resourceAsStream = null;
try {
ClassLoader classLoader = RunoobTblMapperTest.class.getClassLoader();
resourceAsStream = classLoader.getResourceAsStream("mybatis/Mapper.xml");
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryTest.builderSqlSessionFactory(resourceAsStream);
sqlSession = sqlSessionFactory.openSession(true);
mapper = sqlSessionFactory.getConfiguration().getMapper(RunoobTblMapper.class, sqlSession);
}catch (Exception e){
System.out.println(e);
}finally {
resourceAsStream.close();
System.out.println("关闭io连接");
}
}
@After
public void close(){
System.out.println("关闭sqlSession连接");
sqlSession.close();
System.out.println("方法执行完毕!!!");
}
@Test
public void testSelectByPrimaryKey() {
RunoobTbl runoobTbl = mapper.selectByPrimaryKey(1);
System.out.println(runoobTbl);
}
公共构建方法 -- 构建 SqlSessionFactory
public static SqlSessionFactory builderSqlSessionFactory(InputStream resourceAsStream){
UnpooledDataSource ds = new UnpooledDataSource();
ds.setUrl("jdbc:mysql://192.168.56.91:3306/cs007");
ds.setUsername("root");
ds.setPassword("root");
ds.setDefaultNetworkTimeout(30000);
ds.setDriver("com.mysql.cj.jdbc.Driver");
Environment env = new Environment("development", new JdbcTransactionFactory(), ds);
assert resourceAsStream != null;
Reader cfgReader = new InputStreamReader(resourceAsStream);
XMLConfigBuilder parser = new XMLConfigBuilder(cfgReader, null, null);
Configuration cfg = parser.parse();
cfg.setEnvironment(env);
return new SqlSessionFactoryBuilder().build(cfg);
}
configuration 配置
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Mybatis config sample -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="mapperxml/RunoobTblMapper.xml"/>
</mappers>
</configuration>