简体   繁体   中英

Mybatis. Can a session be reused after a commit?

My question is simple. Can a session be reused after a transaction have been committed like this?

try (SqlSession session = sqlSessionFactory.openSession()) {
// following 3 lines pseudocode for "doing some work"
  session.insert(...);
  session.update(...);
  session.delete(...);
  session.commit();

  session.insert();
  session.commit();
}

Or is it better to close a session after a commit, and open a new session?

I'm just starting out with MyBatis as well, and had a similar question about session management. Here's what I've learned so far:

  1. Sessions should be kept open as long as necessary to accomplish your transactions, then closed.
  2. MyBatis provides session-level "local" caching that may be beneficial to your application's performance. Naturally, this depends on your application's design, but generally the longer you keep your session active the better your cache will be. (MyBatis handles cache flushing on commits and rollbacks.)

For your simple example it's fine to keep the session open for those two transactions. Using MyBatis sessions effectively throughout your DAO layer means finding a balance between these two guidelines.

Take the time to go over the official documentation on session management and caching: https://mybatis.github.io/mybatis-3/java-api.html#sqlSessions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM