背景
最近一个采用SSM框架做一个报表系统,在写sql语句过程中,碰到一些sql片段反复出现,于是考虑把这块抽取出来复用。
使用示例
定义代码片段
<sql id="where">STATUS IN (1,2,3,4)</sql>
引用代码片段
SELECT * FROM TEST WHERE <include refid="where"/></sql>
嵌套
<sql id="vals">(1,2,3,4)</sql>
<sql id="where1">STATUS IN <include refid="vals"/></sql>
SELECT * FROM TEST WHERE <include refid="where1"/></sql>
引用另一个xml文件的片段
引用时注意加上命名空间
BaseMapper.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">
<mapper namespace="com.test.BaseDAO">
<sql id="where">STATUS IN (1,2,3,4)</sql>
</mapper>
UserMapper.xml
SELECT * FROM TEST WHERE <include refid="com.test.BaseDAO.where"/></sql>
另一个xml文件中的片段有嵌套
必须写明命名空间
BaseMapper.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">
<mapper namespace="com.test.BaseDAO">
<sql id="vals">(1,2,3,4)</sql>
/*注意以下写了命名空间com.test.BaseDAO,防止UserMapper.xml中引用时报错*/
<sql id="where"> STATUS IN <include refid="com.test.BaseDAO.vals"/></sql>
</mapper>
UserMapper.xml
SELECT * FROM TEST WHERE <include refid="com.test.BaseDAO.where"/></sql>