Sorry Jose, this is difficult to explain.
Let me try it again.
For mybatis, a session and a transaction is the same thing. A session
is like a connection for Jdbc. You change data, and once you are done
you resolve the tx with commit/rollback and close it. Same for
MyBatis.
In Spring a TX is an "scope". A tx is opened and any work you do with
any resource should be attached to that TX. When the TX finishes, all
resources finish with it (with commit or rollback).
Note that when using Spring it is spring who manages the lifecycle of
all objects. There is no session.open() or session.close(). If you try
that methods you will get an exception that tells you that this an
Spring task.
So basically mybatis-spring opens a session when Spring creates a
Transaction and closes it when Spring finishes the transaction.
And.. what happens if there is no transaction and you call mybatis.
Ok, then we open a session, execute the statement and close it. There
is no other option, because there is no place to store that session
and there is not any API to let the user manage it (open, close,
commit). Not a bug! This how we want it to be!
So far so good?
Then, when are connections opened? It depends on mybatis version but
from 3.1 connection opening is delayed untile the fist statement is
executed. Why? Because mybatis uses caches and if all data comes from
the cache there is no point in opening a connection for not using it.
So, if you are not using TX. When you call two statements mybatis does:
- open a session
- open a connection
- execute statement 1
- close a connection (with commit)
- close session
- open a session
- open a connection
- execute statement 2
- close a connection (with commit)
- close session
If using TX
- spring opens a TX
- open a session and attach it to TX
- open a connection
- execute statement 1
- execute statement 2
- spring closes a TX (with commit)
- close session (flush)
- close a connection (with commit)