问答

采用 Configuration 注册 Mapper,他是怎么去加载对应的 mapper.xml 的?
// MapperAnnotationBuilder
private void loadXmlResource() {
// Spring may not know the real resource name so we check a flag
// to prevent loading again a resource twice
// this flag is set at XMLMapperBuilder#bindMapperForNamespace
// xml 的id "namespace:xxx.xx.xx.UserMapper"
if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
// 加载 xml
String xmlResource = type.getName().replace('.', '/') + ".xml";
// #1347
InputStream inputStream = type.getResourceAsStream("/" + xmlResource);
if (inputStream == null) {
// Search XML mapper that is not in the module but in the classpath.
try {
inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
} catch (IOException e2) {
// ignore, resource is not required
}
}
if (inputStream != null) {
// 解析 XMLMapper
XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
xmlParser.parse();
}
}
}`

说明:加载 xml 部分,默认是获取 class.getName,相当于是 package 路径 +.xml 如下:

类路径 org.apache.UserMapper.class

XML 加载路径 org/apache/UserMapper.xml

应该怎么代码配置 MyBatis?
@Test
public void configRegisterMapperTest() {
Configuration configuration = new Configuration();
// 构建 Environment
Environment.Builder builder = new Environment.Builder("11");
builder.dataSource(new UnpooledDataSource(
"com.mysql.jdbc.Driver",
"jdbc:mysql://120.78.218.163:3306/storm_sports",
"root",
"@D23d7a3df91cc42"
));
builder.transactionFactory(new JdbcTransactionFactory());
configuration.setEnvironment(builder.build());
// 添加 mapper
configuration.addMapper(UserMapper.class);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(configuration);
// 开启 sqlSession
SqlSession sqlSession = factory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 查询
UserDO userDO = userMapper.selectById(1L);
sqlSession.close();
System.err.println(userDO);
}

说明:MyBatis 传统模式采用 mybatis-config.xml 配置,配置过程是:

  1. 解析 mybatis-config.xml 配置文件,转换成一个 Document 对象
  2. 采用 xpath 加载 <configuration> 标签内容
  3. 解析 <configuration> 标签内容
MyBatis 有哪些 StatementType 有哪些?
// 直接操作sql,不进行预编译,获取数据:$—Statement
STATEMENT,
// 预处理,参数,进行预编译,获取数据:#—–PreparedStatement:默认
PREPARED,
// 执行存储过程————CallableStatement
CALLABLE