The MyBatis Community (MyBatis.org). Copyright © 2010 ... Why mybatis-spring -
Motivation . .... X release, but unfortunately once released, MyBatis users.
MyBatis-Spring 1.0.0-SNAPSHOT - Reference Documentation
The MyBatis Community (MyBatis.org)
Copyright © 2010
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
1. Introduction .................................................................................................................................. 1 1.1. Why mybatis-spring - Motivation ........................................................................................ 1 1.2. Requirements ..................................................................................................................... 1 1.3. Acknowledgements ............................................................................................................ 1 2. Bootstrap ...................................................................................................................................... 2 2.1. Introduction ....................................................................................................................... 2 2.2. Installation ......................................................................................................................... 2 2.3. Setting up a SqlSessionFactory ........................................................................................... 2 3. Injecting Mappers ......................................................................................................................... 3 3.1. Injecting Mappers .............................................................................................................. 3 4. Using SqlSessionDaoTemplate and SqlSessionDaoSupport ............................................................. 4 4.1. SqlSessionDaoTemplate ..................................................................................................... 4 4.2. SqlSessionDaoSupport ....................................................................................................... 4 5. Using MyBatis API ....................................................................................................................... 5 5.1. Using MyBatis API ............................................................................................................ 5 6. Sample Code ................................................................................................................................ 6 6.1. Sample code ...................................................................................................................... 6
ii
Chapter 1. Introduction 1.1. Why mybatis-spring - Motivation Every Spring user was impatiently waiting for the 3.X release, but unfortunately once released, MyBatis users where terribly disappointed: their preferred SQL Mapping Framework was no more supported. After many request of including the integration and a good number of patches submitted on the Spring Jira issue, once the issue was accepted but announced to be delayed, the MyBatis community thought it was time to reunite the interested people and contributors and start the Spring integration made by the community itself. So, this small library intends to create the missing perfect glue between the two popular frameworks, reducing the boilerplate and redundant code that users have to write to configure and use MyBatis into a Spring 3.X context.
1.2. Requirements Before starting reading the manual, it is very important you're familiar with both MyBatis and Spring framework and terminology, otherwise it would be very difficult to understand the described context. Like MyBatis, mybatis-spring requires Java 5 or higher.
1.3. Acknowledgements A special thanks goes to all the special people who made this project a reality. Hunter Presnall, Putthibong Boonbong who made all the hard coding, Eduardo Macarron for the MapperFactoryBean and documentation, Andrius Juozapaitis, Giovanni Cuccu, Raj Nagappan for their contributions and support and Simone Tripodi for finding them and bringing them all to the project ;) Without them, that project wouldn't exist.
1
Chapter 2. Bootstrap 2.1. Introduction Mybatis-spring integration helps you to integrate your code seamlessly with Spring. Spring will load and create necessary MyBatis classes for you, will handle transactions, translate exceptions and will also inject mappers into your service beans.
2.2. Installation To run mybatis-spring module you just need to include the mybatis-spring-1.0.0-SNAPSHOT.jar file and its dependencies in the classpath. If you are using Maven just add the following dependency to your pom.xml : org.mybatis mybatis-spring 1.0.0-SNAPSHOT
2.3. Setting up a SqlSessionFactory As you already know, to use MyBatis you need to build a SqlSessionFactory. Mybatis-spring will build it for you during Spring startup. The XML snippet below shows the configuration needed to build a SqlSessionFactoryBean:
As you see to set a SqlSessionFactory you will just need a datasource. You can also provide a mybatis-config.xml by seting the configLocation property:
When using mybatis-spring you should not include the transactionManager and dataSource sections in your mybatis-config.xml. Mapper list is also not needed when using injected mappers.
2
Chapter 3. Injecting Mappers 3.1. Injecting Mappers Mybatis-spring lets you inject mappers into your service beans. When using mappers you simply call your mappers as you have always called your DAOs, but this time you won´t need to code any DAO implementation because MyBatis will do it for you. With injected mappers your code will have no mybatis-spring dependencies and no MyBatis dependencies either. We have this simple mapper in our application. As you know a mapper is just an interface: public interface UserMapper { User getUser(String userId); }
This is the way you set up this mapper with mybatis-spring:
When using mappers you don't need to set up mapper list on the mybatis-config.xml file because mappers are able to register themselves to MyBatis during startup. Now your mapper is ready to be injected on your service objects:
3
Chapter 4. Using SqlSessionDaoTemplate and SqlSessionDaoSupport 4.1. SqlSessionDaoTemplate If you need to use MyBatis SqlSession you should use SqlSessionDaoTemplate. This object is able to create a new SqlSession or get the active SqlSession from current transaction. It also translates exceptions to Spring's generic DataAccessException hierarchy. A SqlSessionDaoTemplate can be created using a SqlSessionFactory as a constructor argument. SqlSessionDaoTemplate sessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
As the following snippet shows, instead of using a SqlSession you use SqlSessionDaoTemplate to execute MyBatis methods (selectOne, selectList...): public User getUser(String userId) { return (User) sessionTemplate.selectOne("sample.UserMapper.getUser", userId); }
The SqlSessionDaoTemplate also offers a generic method, taking a custom SqlSessionCallback as argument so that you can execute more than one method over a SqlSession: public void insertUser(final User user) { getSqlSessionTemplate().execute(new SqlSessionCallback() { public Object doInSqlSession(SqlSession sqlSession) throws SQLException { sqlSession.insert("sample.UserMapper.insertUser", user); sqlSession.insert("sample.UserMapper.insertAccount", user.getId()); return null; } }); }
4.2. SqlSessionDaoSupport SqlSessionDaoSupport is a support class that simply builds a SqlSessionDaoTemplate for you so that you can use by calling getSqlSessionTemplate() as follows: public class UserMapperDaoImpl extends SqlSessionDaoSupport implements UserMapper { public User getUser(String userId) { return (User) getSqlSessionTemplate().selectOne("sample.UserMapper.getUser", userId); } }
4
Chapter 5. Using MyBatis API 5.1. Using MyBatis API You can also use directly MyBatis API. In this case you won't have any mybatis-spring dependency and you simply use a injected SqlSessionFactory on your DAOs: public class UserMapperSqlSessionImpl implements UserMapper { private SqlSessionFactory sqlSessionFactory; public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } public User getUser(String userId) { SqlSession session = sqlSessionFactory.openSession(); try { User user = (User) session.selectOne("sample.UserMapper.getUser", userId); return user; } finally { session.close(); } } }
In this scenario SqlSessions will not be reused within a transaction and there will be no exception translation. Spring transaction management will still work over the inner database connection.
5
Chapter 6. Sample Code 6.1. Sample code You can have a look or check out sample code from MyBatis repository on Google Code. • Java code • Config files To run the sample just run MyBatisSampleTest.java with JUnit 4. acts as a transactional service. It starts and ends a transaction when any of its methods is called. Have a look to FooService.java to see how transactional behaviour is configured with the @Transactional attribute. This is just a sample, you can use any other way provided by Spring to demarcate your transactions. FooService
@Transactional public interface FooService { User doSomeBusinessStuff(String userId); }
is the FooService implementation and it just uses DAOs/mappers that Spring has injected during startup. You will notice that your code does not need to call any Spring or Mybatis methods. FooServiceImpl.java
public class FooServiceImpl implements FooService { private UserMapper userMapper; public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public User doSomeBusinessStuff(String userId) { return this.userMapper.getUser(userId); } }
The database access layer has been implemented using the three different techniques explanied in this manual. Have a look at context.xml.
6