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。