针对上述的xml配置,可以使用如下的java代码替换:
@Test
public void testConfiguration() {
Configuration configuration = new Configuration();
// 配置properties
Properties properties = new Properties();
properties.put("driver", "com.mysql.cj.jdbc.Driver");
properties.put("url", "jdbc:mysql://localhost:3306/dcyMybatis");
properties.put("username", "root");
properties.put("password", "root");
configuration.setVariables(properties);
// 配置日志处理器
configuration.setLogImpl(Slf4jImpl.class);
// 配置驼峰命名
configuration.setUseActualParamName(true);
// 配置别名注册器注册一个包
configuration.getTypeAliasRegistry().registerAliases("com.dcy.entity");
// 配置Environments的 id、事务工厂、数据源
JdbcTransactionFactory jdbcTransactionFactory = new JdbcTransactionFactory();
PooledDataSource pooledDataSource = new PooledDataSource();
pooledDataSource.setDriver(configuration.getVariables().getProperty("driver"));
pooledDataSource.setUrl(configuration.getVariables().getProperty("url"));
pooledDataSource.setUsername(configuration.getVariables().getProperty("username"));
pooledDataSource.setPassword(configuration.getVariables().getProperty("password"));
Environment environment = new Environment("development", jdbcTransactionFactory, pooledDataSource);
configuration.setEnvironment(environment);
// 配置Mapper
StaticSqlSource staticSqlSource = new StaticSqlSource(configuration,"insert into account (username,money) values ('Cat', 291)");
MappedStatement mappedStatement = new MappedStatement.Builder(
configuration,
"dcy.insert",
staticSqlSource,
SqlCommandType.INSERT
).build();
configuration.addMappedStatement(mappedStatement);
}
所有的mybatis.xml的配置项都可以使用Configuration类的形式进行配置
一个包装了XPathParser的工具类XMLConfigBuilder,可以将xml的配置文件解析成为一个配置类Configuration,代码如下:
@Test
public void tesXMLConfigBuilder() throws IOException {
InputStream inputStream = new ClassPathResource("mybatis.xml").getInputStream();
XMLConfigBuilder xmlConfigBuilder = new XMLConfigBuilder(inputStream);
Configuration configuration = xmlConfigBuilder.parse();
log.info("Configuration -> {}", configuration);
}