Requesting Injections

Getting an SqlSession

In MyBatis you use the SqlSessionFactory to create an SqlSession. Once you have a session, you use it to execute your mapped statements, get mappers, commit or rollback connections and finally, when it is no longer needed, you close the session. With MyBatis-Guice you don't need to use SqlSessionFactory directly because your beans can be injected with a thread safe SqlSession that automatically commits, rollbacks and closes the session based on @Transactional annotation.

public class UserDaoImpl implements UserDao {

    private SqlSession sqlSession;

    public User getUser(String userId) {
        return (User) this.sqlSession.selectOne("org.mybatis.guice.sample.mapper.UserMapper.getUser",


Getting Mappers

Rather than code data access objects (DAOs) manually using SqlSession, Mybatis-Guice is able to inject data mapper interfaces directly into your service beans. When using mappers you simply call them as you have always called your DAOs, but you won't need to code any DAO implementation because MyBatis-Guice will create a proxy for you. When using mappers you will not even see the inner SqlSession, but not worries, it will just work.

public class FooServiceMapperImpl implements FooService {

    private UserMapper userMapper;

    public User doSomeBusinessStuff(String userId) {
        return this.userMapper.getUser(userId);