Here, any kind of DataSource is allowed. For example, org.springframework.jdbc.jar:
I got CannotGetJdbcConnectionException when coded my SpingMVC + Mybatis Helloworld example. The solution is to add ?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT. So set explicitly unicode and timezone.
In previous note MyBatis Basic, we get SqlSessionFactory by SqlSessionFactoryBuilder:
But in MyBatis-Spring xml, bean SqlSessionFactory is created by SqlSessionFactoryBean:
Two ways to define:
When using xml based:
Tell SqlSessionFactoryBean where to find it by mapperLocations.
Mapper namespace must be full package path to mapper interface.
id must be the same as function name in mapper interface, also the resultType, paramType, etc.
The following example mixed both of xml and annotation.
In previous note MyBatis Basic, we get SqlSession from SqlSessionFactory and do transaction manually like following.
But in mybatis-spring, beans will be injected with a thread safe SqlSession that automatically commits, rollbacks and closes the session based on Spring’s transaction configuration.
We have two ways to get sesion in DAOs:
But I prefer to use MapperScannerConfigurer or MapperFactoryBean directly to avoid coding DAOs manually. MapperScannerConfigurer could even automatically scan mapper interfaces. It’s the beat choice!
So first, in mybatis-spring, just need to enable Spring transaction processing:
Then add @Transactional annotation on service layer.
SqlSessionTemplate implements SqlSession. It is thread safe and can be shared by multiple DAOs or mappers. It is used to:
Ensure that SqlSession used is the one associated with the current Spring transaction when call SQL method.
Manage session life-cycle, including closing, committing or rolling back the session as necessary.
Translate MyBatis exceptions into Spring DataAccessExceptions.
So the idea here is to create a bean of SqlSessionTemplate and inject it in DAO layer:
DAO class with injected sqlSession:
To enable batch feature:
Now all SQL statements will be batched:
It is an abstract support class that provides SqlSession. We could call getSqlSession() by extending SqlSessionDaoSupport to get SqlSession:
It is used to avoid coding manually DAOs by SqlSessionDaoSupport or SqlSessionTemplate, so no DAOs here in java code! It handles creating an SqlSession as well as closing it. If there is a Spring transaction in progress, the session will also be committed or rolled back when the transaction completes.
With MapperFactoryBean, we need to declare a bean for each mapper interface. So better to use MapperScannerConfigurer to automatically scan to find mapper interfaces and register each of them as a MapperFactoryBean.
IDE will mention Could not autowired, it’s because each MapperFactoryBean is created by MapperScannerConfigurer, IDE could not find yet an existing implementation, D’ont worry. (To check, at least, when I tried my helloworld, it works fine even with this error check)