MyBatis
Posted by Bruce Tsai
03/10/2016
透過 XML 與 Mapper 來處理 SQL query
MyBatis 是一個 Java 持久化框架,為 iBATIS 3.0(retired) 的分支版本,它通過 XML 描述符或註解把物件與儲存過程或 SQL 語句關聯起來。同時也支援與 Spring 的整合。
以 XML 與 Mapper 進行查詢
<?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" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
在 XML 中以使用邏輯條件組合查詢
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
以介面設定 annotation 進行查詢
public interface BlogMapper {
@Select("SELECT * FROM blog WHERE id = #{id}")
Blog selectBlog(int id);
}
SqlSession session = sqlSessionFactory.openSession();
try {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(id);
// do work
} finally {
session.close();
}