1):定义sql片段
<!-- 定义sql片段 -->
<!--
id: sql片段的标识
经验:1:基于单表来定义sql片段,这样的话sql片段的可重用性才高
2:sql片段中不要包含<where>标记
-->
<sql id="where_statement">
<if test="_parameter!=null">
<if test="username!=null and username!=‘‘">
t.username like ‘%${username}%‘
</if>
<if test="sex!=null and sex!=‘‘">
and t.sex=#{sex}
</if>
</if>
</sql>
2):使用sql片段
<!-- 查询用户信息 -->
<select id="queryUser5" parameterType="org.pine.mybatis.util.UserQueryBean" resultType="org.pine.mybatis.po.User">
select t.id,t.username,t.birthday,t.sex,t.address
from user t
<where>
<!-- 使用sql片段 -->
<!-- <include refid="where_statement"/> -->
<!-- 注意:如果要使用其它映射文件(StaffMapper.xml)中定义的sql片段,需要加上其它映射文件(StaffMapper.xml)中的namespace -->
<include refid="org.pine.mybatis.mapper.StaffMapper.where_statement1"/>
</where>
</select>
3):进行测试
@Test
public void testQueryUser5(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserQueryBean userQueryBean = new UserQueryBean();
String username = "李";
String sex = "男";
userQueryBean.setUsername(username);
userQueryBean.setSex(sex);
List<User> users = userMapper.queryUser5(userQueryBean);
for (int i = 0; i < users.size(); i++) {
User user = users.get(i);
logger.info(i+"==>"+user);
}
sqlSession.close();
}
原文地址:https://www.cnblogs.com/thaipine/p/10202572.html