Home  >  Q&A  >  body text

java - Mybais 会话session是否公用

问题:使用mybatis时,一个sqlsessionfactory.opensession的方法,能否同时兼容多个dao的操作
例如,我在pojo a 的dao,aDAO的插入操作中,实例化了一个session,
SqlSession session = sqlSessionFactory.openSession();
ADAO aDAO = session.getMapper(ADAO.class);
此时由于我要同时对pojo b进行一些操作,那么我可不重新实例化新的session,而是直接使用之前实例的session a
BDAO bDAO = session.getMapper(BDAO.class)

如果可以这么操作的话,请问有什么限制(因为如果是删除,增加,更新的操作的话,是需要提交会话的,而查询不需要)

ringa_leeringa_lee2727 days ago589

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-17 18:00:32

    1. mybatis中通过SqlSessionManager这个类来管理Session的话,每一个线程是公用的一个Session

    2. mybatis-spring这个集成插件中,对于没有启用事务的一条查询/更新语句对应一个Session,如果开启了事务,在这个事务中的查询/更新都是公用一个Session

    3. mybatis中的Executor不是线程安全的,所以最多只能在一个线程中复用Session

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 18:00:32

    A session can of course operate multiple DAOs (including add/delete/modify/check). Of course, these DAO operations must meet the characteristics of transactions when the session is submitted/rolled back: either all modifications are successful, or all of them fail. The only restriction is: because they are in the same session, these DAOs must access the same Database.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 18:00:32

    Yes, except as mentioned above, these dao access the same database, please note that the session is not thread-safe

    reply
    0
  • Cancelreply