General

What is MyBatis? Is it an ORM?

MyBatis is a persistence framework that automates the mapping between SQL & Objects. The mapping is automated by packaging the SQL in XML files. The benefits are:

1. Reduction of amount of code (for DB access)

2. Prevention from code mistakes such as: Open Connection, Coding a wrong mapping, fetching more results when one is required, etc.

3. Easy integration with frameworks like Spring, Guice.

3. These benefits comes with no reduction of Control on SQL.

Hibernate vs MyBatis

Hibernate

ORM

Object centric

MyBatis

SQL to Object Mapping framework

Database Centric

How to use MyBatis?

1. SQLSessionFactoryBuilder - ThreadSafe class to create SGLSessionFactory. Ideally create one object per application.

2. SQLSessionFactory - ThreadSafe class to create SQLSessions. Ideally create one object per application.

SQLSessionFactory sglSessionFactory = new SQLSessionFactoryBuilder().build("pathOfConfigurationFile");

SQLSessionFactory sglSessionFactory = new SQLSessionFactoryBuilder().build(configurationObject);

3. SQLSession - Thread unsafe, should be used one per thread. This takes parameters to decide what type of transactions (bean or container managed).

SQLSession sqlSession = sqlSessionFactory.openSession()

This sqlSession is the ultimate object that will be used for database transactions. It encapsulates the connection object. SQLSession will be used to manage the transactions.

Using SQLSession:

a. Use the SQLSession as normal DAO e.g.

sqlSession.selectOne("someMapper.someMethod");

sqlSession.select("select * from tab1");

b. Mapper Interface -

Create an interface Mapper (e.g. BlogMapperInterface)

Create the Mapper XML defining the method with appropriate SQLs,

<mapper namespace="org.mybatis.example.BlogMapperInterface">

<select id="selectBlog" parameterType="int" resultType="Blog">

select * from Blog where id = #{id}

</select>

</mapper>

BlogMapperInterface mapper = session.getMapper(BlogMapperInterface.class);

How Transactions are managed in MyBatis?

MyBatis & Spring