MyBatis is a framework for mapping objects to relational databases with an emphasis on high performance and simplicity. XML descriptors or annotations couple the objects to SQL statements or stored procedures.
MyBatis is a framework for mapping objects (Java and .NET) to relational databases with an emphasis on simplicity. The objects are coupled with SQL statements and/or stored procedures using XML descriptor files. Unlike ORM frameworks MyBatis does not map Java objects to database tables but methods to SQL statements.
MyBatis is lightweight and quite easy to use since the only parts involved are the own objects, XML and SQL. It also integrates with the Spring framework.
Example mapping file:
<sqlMap namespace="CUSTOMER">
<resultMap class="com.example.Customer" id="CustomerMapping">
<result column="CUSTOMER_ID" property="customerId" jdbcType="DECIMAL" />
<result column="NAME" property="name" jdbcType="VARCHAR" />
</resultMap>
<select id="CUSTOMER.selectByPrimaryKey" parameterClass="java.lang.Long" resultMap="CustomerMapping">
<![CDATA[
SELECT customer_id,
name
FROM customer
WHERE customer_id = #id:DECIMAL#
]]>
</select>
</sqlMap>
Simple usage:
Interface:
package org.mybatis.example;
public interface BlogMapper {
@Select("select * from Blog where id = #{id}")
Blog selectBlog(int id);
}
Using interface:
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
SQL statements and mappings can also be externalized to an XML file like this:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" parameterType="int" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
Spring integration:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="blogMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<property name="mapperInterface" value="org.mybatis.example.BlogMapper" />
</bean>
<bean id="blogService" class="org.mybatis.example.BlogServiceImpl">
<property name="blogMapper" ref="blogMapper" />
</bean>
In code you just use blogMapper interface:
public class BlogServiceImpl implements BlogService {
private BlogMapper blogMapper;
public void setBlogMapper(BlogMapper blogMapper) {
this.blogMapper = blogMapper;
}
public void doSomethingWithABlog(int blogId) {
Blog blog = blogMapper.selectBlog(blogId);
// ...
}
}
Resources