Spring 4 + MyBatis 3 Example with MapperScan and SqlSessionFactoryBean
By Arvind Rai, March 23, 2015
In this page we will provide Spring 4 and MyBatis 3 Example with MapperScan and SqlSessionFactoryBean. MyBatis provides their API for Spring integration. MyBatis MapperScan annotation scans all mapper interfaces for the given package and makes it available to the spring configuration class. MyBatis implements the mapper interfaces and performs mapper injection in spring implementation classes. We create a bean of MyBatis SqlSessionFactoryBean which provides SqlSession. For transaction management MyBatis uses spring's DataSourceTransactionManager. We need to create a bean of DataSourceTransactionManager in spring configuration class. Transaction is saved by spring MyBatis API and if any error, transactions is roll backed. Here in this page, we will provide a complete example for spring MyBatis integration step by step.
Software Required to Run Example
We are using below software and tool to run our demo. 1. Java 7 2. Eclipse 3. Gradle 4. MySQL
Table Schema
Find the table which we are using in our demo project. Table: village
Create Spring Configuration Class using SqlSessionFactoryBean and MapperScan
We will create a spring configuration class for bean definition. To access mapper interfaces, MyBatis provides MapperScan annotation which will scan mapper interfaces. In mapper interfaces we define our SQL queries.
MapperScan: Scans the mapper interfaces for MyBatis. MapperScan annotation is used when we are using spring configuration class for bean definition. SqlSessionFactoryBean: Provides SqlSesion used by MyBatis. DataSourceTransactionManager: For transaction management MyBatis uses spring's DataSourceTransactionManager.
In DataSource bean, we perform database configurations which is used by SqlSessionFactoryBean and DataSourceTransactionManager bean. Find the configuration class now. AppConfig.java