How to close a database connection in MyBatis?

By default, MyBatis will automatically close the database connection after each database operation, but it can also be manually closed.

You can manually close the database connection using the following method:

  1. Add the following configuration in the configuration file (mybatis-config.xml) to set the behavior when the database connection pool is closed:
<configuration>
  <environments default="development">
    <environment id="development">
      <!-- ... -->
      <dataSource type="..." />
      <transactionManager type="..." />
      <!-- ... -->
    </environment>
  </environments>
  
  <!-- 添加以下配置项 -->
  <properties>
    <property name="closeConnection" value="true" />
  </properties>
</configuration>
  1. Manually close the database connection in the code.

After performing database operations using the SqlSession object, call its close() method to close the database connection. For example:

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
  // 执行数据库操作
} finally {
  sqlSession.close();
}

If you are using the Spring framework, it will automatically manage the opening and closing of database connections, so there is no need to manually close them.

Leave a Reply 0

Your email address will not be published. Required fields are marked *