Scope and lifecycle


Scope and lifecycle

Different scopes and lifecycle categories are crucial because incorrect use can lead to very serious concurrency problems.

  • This class can be instantiated, used, and discarded. Once sqlsessionfactory is created, it is no longer needed.
  • local variable


  • To put it bluntly, it can be imagined as: database connection pool
  • Once sqlsessionfactory is created, it should always exist during the running of the application,There is no reason to discard it or recreate another instance.
  • Therefore, the best scope of sqlsessionfactory is the application scope.
  • The simplest is to use singleton mode or static singleton mode.


  • A request to connect to the connection pool
  • The instance of sqlsession is not thread safe, so it cannot be shared, so its best scope is the request or method scope.
  • It must be closed after use, otherwise it will cause great memory resource overhead!

Scope and lifecycle
Every mapper here represents every specific business!