mybatis初识

mybatis官网对scope和lifecycle划了重点:

SqlSessionFactoryBuilder
  There is no need to keep it around once you've created your SqlSessionFactory. Therefore the best scope for instances of SqlSessionFactoryBuilder is method scope (i.e. a  local method variable). You can reuse the SqlSessionFactoryBuilder to build multiple SqlSessionFactory instances.

SqlSessionFactory
  Once created, the SqlSessionFactory should exist for the duration of your application execution. This can be achieved a number of ways. The simplest is to use a Singleton  pattern or Static Singleton pattern.

SqlSession
  Each thread should have its own instance of SqlSession. Instances of SqlSession are not to be shared and are not thread safe. Therefore the best scope is request or method scope. Never keep references to a SqlSession instance in a static field or even an instance field of a class.  Closing the session is very important. You should always ensure that it's closed within a finally block. The following is the standard pattern for ensuring that SqlSessions are closed:

SqlSession session = sqlSessionFactory.openSession();
try {
  // do work
} finally {
  session.close();
}

Mapper Instances: method scope

猜你喜欢

转载自www.cnblogs.com/crazyRanZhang/p/9255790.html