2 G e t t i n g S t a r t e d
6
2.1.5.3 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. Never keep references to a
SqlSession in any sort of managed scope, such as HttpSession of of the Servlet framework. If you're
using a web framework of any sort, consider the SqlSession to follow a similar scope to that of an
HTTP request. In other words, upon receiving an HTTP request, you can open a SqlSession, then
upon returning the response, you can close it. 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();
}
Using this pattern consistently throughout your code will ensure that all database resources
are properly closed.
2.1.5.4 Mapper Instances
Mappers are interfaces that you create to bind to your mapped statements. Instances of the mapper
interfaces are acquired from the SqlSession. As such, technically the broadest scope of any mapper
instance is the same as the SqlSession from which they were requested. However, the best scope for
mapper instances is method scope. That is, they should be requested within the method that they are
used, and then be discarded. They do not need to be closed explicitly. While it's not a problem to keep
them around throughout a request, similar to the SqlSession, you might find that managing too many
resources at this level will quickly get out of hand. Keep it simple, keep Mappers in the method scope.
The following example demonstrates this practice.
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
// do work
} finally {
session.close();
}
NOTE Object lifecycle and Dependency Injection Frameworks
Dependency Injection frameworks can create thread safe, transactional SqlSessions and mappers and
inject them directly into your beans so you can just forget about their lifecycle. You may want to
have a look at MyBatis-Spring or MyBatis-Guice sub-projects to know more about using MyBatis
with DI frameworks.
© 2 0 1 3 , M y B a t i s . o r g • A L L R I G H T S R E S E R V E D .