官方文档说明
bind
bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。比如:
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
具体例子如下
1、单个参数时
JAVA:
TC_ENTR_FLOW selectFlowForUpdate(String ENTR_ID);
XML:
<select id="selectFlowForUpdate" resultMap="BaseResultMap"
parameterType="java.lang.String">
<bind name="ENTR_ID" value="'%' + _parameter" />
select * from TC_ENTR_FLOW where ENTR_ID like #{ENTR_ID}
</select>
这里,参数名称必须是_parameter,否则会提示异常。
例如,将_parameter改为_parameter1,出现如下提示。
"nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named '_parameter1' in 'class java.lang.String'", "data": null,
2、多个参数时,利用Map
JAVA
List<UserViewVO> select(Map<String,String> param);
XML
<select id="select" parameterType="map" resultMap="UserViewMap">
<if test="queryValue != null">
<bind name="pattern1" value="'%' + queryValue + '%'" />
</if>
select * from T_SYS_USER
<where>
1 = 1
<if test="queryValue != null">
and name like #{pattern1}
</if>
</where>
</select>
这里,queryValue是参数Map中的key值。
3、多个参数,利用JAVA对象
JAVA
List<Blog> selectBlogsLike(Blog blog);
class Blog{
private String title;
setTitle...
getTitle...
}
XML
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
上面这种方式,是官方文档中的,肯定可以。
下面这种方式,也是可以的。
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + title + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
使用bind拼接字符串不仅可以避免因更换数据库而修改SQL,也能预防SQL注入。