How can MyBatis achieve configuration loading?
MyBatis can load configuration in two ways.
- A builder for SqlSessionFactory
- construct()
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- Java code configuration loading: It is possible to configure MyBatis by writing Java code instead of using XML files. An example code is shown below:
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);
These are two common ways to load configuration settings for MyBatis. Choose the appropriate method based on your specific situation.