目的是为了提高xml文件中sql的复用性。
因为跟着很多帖子试下来都不行,特意在csdn发问答帖(如何在mybatis的xml文件中,include另一个xml文件中的sql-Java-CSDN问答)解决后,过了半个月又不行了。
故重新整理一篇帖子。
首先看我工程里mapperLocations配置:
mapperLocations: classpath*:mapper/**/*Mapper.xml
这意味着mapper目录下的所有目录下名为*Mapper.xml的xml文件都会被扫描。
这样以来事情就简单了:
1.建立一个公共的xml文件,我的叫CommonMapper.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="CommonTest">
<sql id="searchByLevel">
#通用sql
</sql>
</mapper>
注:
namespace需要定义一个名字,会报红,但这不影响什么,当然也有不报红的办法,本帖不做赘述;
id需要定义为一个唯一的id。
2.在需要调用这个公共sql代码块的地方调用即可:
<select id="getInfo" resultType="com.demo.vo.UserInfo">
select
*
from UserInfo
<where>
<include refid="CommonTest.searchByLevel"/>
</where>
</select>