MyBatis Tutorial : Part4 – Spring Integration

MyBatis Tutorial: Part1 – CRUD Operations

MyBatis Tutorial: Part-2: CRUD operations Using Annotations

MyBatis Tutorial: Part 3 – Mapping Relationships

MyBatis Tutorial : Part4 – Spring Integration

MyBatis-Spring is a sub-project of MyBatis that provides Spring integration support, which drastically simplifies MyBatis usage. For those who are familiar with Spring’s Dependency Injection process, using MyBatis-Spring is very simple.

First, let us see the process of using MyBatis without Spring.

  1. Create SqlSessionFactory using SqlSessionFactoryBuilder by passing mybatis-config.xml, which contains DataSource properties, a list of Mapper XMLs, TypeAliases, etc.
  2. Create an SqlSession object from SqlSessionFactory.
  3. Get a Mapper instance from SqlSession and execute queries.
  4. Commit or roll back the transaction using the SqlSession object.

With MyBatis-Spring, most of the above steps can be configured in the Spring ApplicationContext, and SqlSession or Mapper instances can be injected into Spring Beans. Then we can use Spring’s TransactionManagement features without writing transaction commit/rollback code all over the place.