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 {

    @Inject
    private SqlSession sqlSession;

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

}

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.

@Singleton
public class FooServiceMapperImpl implements FooService {

    @Inject
    private UserMapper userMapper;

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

}