有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用即可。
- 使用sql标签提取公共的部分
<sql id="selectBlog">
select id,title,author,create_time,views from blog
</sql>
- 在需要使用的地方使用include标签引用即可
<select id="query" parameterType="blog" resultType="map">
<include refid="selectBlog"/>
<where>
<if test="title!=null">
and title=#{title}
</if>
</where>
</select>
测试:
@org.junit.Test
public void test(){
//通过封装好的工具类获取SqlSession会话
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//通过接口类型class获取接口对象实例(动态代理)
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
//执行接口中的方法
HashMap<String,Object> map=new HashMap<String, Object>();
map.put("title","Java如此简单2");
mapper.query(map);
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
结果:
注意: 最好基于单表来定义sql片段,提高片段的可重用性
如果引用其他Mapper.xml中的sql片段,则需要在include标签中属性refid中加上引用Mapper.xml中的namespace.sql片段的id.
示例:
另一个接口类:
public interface UserMapper {
List<Blog> query(Map map);
}
另一个UserMapper.xml文件
<?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">
<!--namespace绑定一个对应的dao/mapper接口-->
<mapper namespace="dao.UserMapper">
<sql id="select">
select * from blog
</sql>
</mapper>
当前Mapper.xml中引用UserMapper.xml中的sql片段
<select id="query" parameterType="blog" resultType="map">
<!-- namespace.sql(id)-->
<include refid="dao.UserMapper.select" />
<where>
<if test="title!=null">
and title=#{title}
</if>
</where>
</select>
测试类:
@org.junit.Test
public void test(){
//通过封装好的工具类获取SqlSession会话
SqlSession sqlSession = MyBatisUtils.getSqlSession();
//通过接口类型class获取接口对象实例(动态代理)
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
//执行接口中的方法
HashMap<String,Object> map=new HashMap<String, Object>();
map.put("title","Java如此简单2");
mapper.query(map);
sqlSession.commit();
//关闭SqlSession
sqlSession.close();
}
结果: