Creating a new SqlSession
时间: 2024-01-07 10:44:18 浏览: 78
To create a new SqlSession in Java, you first need to obtain a SqlSessionFactory object. This can be done using a configuration file or programmatically. Once you have the SqlSessionFactory, you can use it to create new SqlSession instances.
Here is an example of creating a SqlSession using a configuration file:
```
// Load configuration file
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// Open new session
SqlSession sqlSession = sqlSessionFactory.openSession();
```
Alternatively, you can create a SqlSessionFactory programmatically and use it to create a new SqlSession:
```
// Create configuration object
Configuration config = new Configuration();
config.setJdbcUrl("jdbc:mysql://localhost:3306/mydatabase");
config.setUsername("username");
config.setPassword("password");
// Create SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
// Open new session
SqlSession sqlSession = sqlSessionFactory.openSession();
```
Remember to close the SqlSession when you are finished using it, to release resources:
```
sqlSession.close();
```
阅读全文