1、本文中主要针对***if、where、foreach、sql***标签,进行应用介绍。
2、if、where、sql
SQL映射文件应用:
<!--使用SQL标签,截取出重复使用SQL,可以再其他SQL标签中引用-->
<sql id="defaultSql">
select * from user
</sql>
<!--动态SQL where、if标签-->
<select id="queryUserByMap" resultMap="resultMap" parameterType="Map">
<!--此处使用include标签引用上例sql标签中的查询SQL-->
<include refid="defaultSql"></include>
<where>
<if test="userName != null and userName != ''">
and username = #{userName}
</if>
<if test="ADDRESS != null and ADDRESS != ''">
and address like '%${ADDRESS}%'
</if>
<if test="Ids != null and Ids != ''">
and id || '' in (#{Ids}) <!--此处传参为String类型,需要把数据库中Integer类型的id转换成String类型然后进行查询-->
</if>
</where>
</select>
注:需要注意的是在此处SQL中传入的参数类型时Map类型,并不是封装实体类,同样的返回参数也可以使用相似方法,此种用法在mybatis中是支持的。
接口:
/**
* 使用Map集合作为参数类型
* 动态SQL -- If、where、sql标签
*/
List<userCRUDModelTwo> queryUserByMap(Map<String,String> map);
测试方法:
/**
* 动态SQL : if、where、sql
*/
@Test
public void queryUserByMap(){
Map<String,String> map = new HashMap<>();
map.put("userName","老王");
map.put("ADDRESS","北京");
map.put("Ids","'41','42','49','50','51'");
List<userCRUDModelTwo> list = iuCRUD.queryUserByMap(map);
for (userCRUDModelTwo model : list
) {
System.out.println(model);
}
/**
* Preparing: select * from user WHERE username = ? and address like '%北京%'
*/
}
3、foreach标签应用实例:
SQL映射文件:
<!--动态SQL foreach标签-->
<select id="queryUserByForeach" resultMap="resultMap" parameterType="List">
<include refid="defaultSql"></include>
<where>
<if test="list != null and list.size() > 0">
<!--foreach标签中属性解析:
collection:集合
open:开始属性
close:结束属性
item:取值放入位置
separator:循环取值之间的间隔符
-->
<foreach collection="list" open="and id in(" close=")" item="uid" separator=",">
#{uid} <!--此处占位符名称取决于foreach标签中item属性的值-->
</foreach>
</if>
</where>
</select>
注:此处使用的foreach标签实现的效果可以可 2 实例中参数ids的实现效果做对比;
sql中参数类型为List集合类型。
接口:
/**
* 动态SQL -- foreach
*
*/
List<userCRUDModelTwo> queryUserByForeach(List<Integer> list);
测试方法;
/**
* 动态SQL -- foreach标签
*/
@Test
public void queryUserByForeach(){
List<Integer> list = new ArrayList<>();
list.add(41);
list.add(48);
list.add(49);
list.add(50);
List<userCRUDModelTwo> resultList = iuCRUD.queryUserByForeach(list);
for (userCRUDModelTwo model:resultList
) {
System.out.println(model);
}
}