MyBatis可以通过两种方式来加载配置:
SqlSessionFactoryBuilder
类的build()
方法加载配置文件。示例代码如下:String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
DataSource dataSource = ... // 创建数据源对象
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(MyMapper.class); // 添加Mapper接口
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
以上是两种常用的加载配置的方式,根据实际情况选择适合的方式来配置和加载MyBatis。