简介
在Mybatis3的源码解析系列中,我们对其核心功能有了一定的了解,下面我们尝试简单写一下Demo,让其有简单的Mybatis的一些核心功能,本篇是基础功能的搭建
Dome 编写
完整的工程已放到GitHub上:https://github.com/lw1243925457/MybatisDemo/tree/master/
本篇文章的代码对应的Tag是: V1
本篇的目标是完成MapperProxy和运行不带参数和无自定义返回类型的SQL
测试代码如下:
public class SelfMybatisTest {
@Test
public void test() {
try(SelfSqlSession session = buildSqlSessionFactory()) {
PersonMapper personMapper = session.getMapper(PersonMapper.class);
personMapper.createTable();
personMapper.save();
List<Object> personList = personMapper.list();
for (Object person: personList) {
System.out.println(person.toString());
}
}
}
public static SelfSqlSession buildSqlSessionFactory() {
String JDBC_DRIVER = "org.h2.Driver";
String DB_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
String USER = "sa";
String PASS = "";
HikariConfig config = new HikariConfig();
config.setJdbcUrl(DB_URL);
config.setUsername(USER);
config.setPassword(PASS);
config.setDriverClassName(JDBC_DRIVER);
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
DataSource dataSource = new HikariDataSource(config);
SelfConfiguration configuration = new SelfConfiguration(dataSource);
// configuration.getTypeHandlerRegistry().register(String[].class, JdbcType.VARCHAR, StringArrayTypeHandler.class);
configuration.addMapper(PersonMapper.class);
return new SelfSqlSession(configuration);
}
}
如上所示,我们集成其他DataSource,这里使用HikariCP,然后初始化Mapper,生成表、插入、查询
最终的结果如下:
初始化我们的PersonMapper,最后输出查询的结果
add sql source: mapper.mapper.PersonMapper.list
add sql source: mapper.mapper.PersonMapper.save
add sql source: mapper.mapper.PersonMapper.createTable
executor
executor
executor
[1, 1]
基本达到了要求,下面开始讲解核心代码: