首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Ibatis 之 $ &

2012-08-14 
Ibatis 之 $ & #Ibatis 之 $ & #?在Ibatis中我们使用SqlMap进行Sql查询时需要引用参数,在参数引用中遇到的

Ibatis 之 $ & #

Ibatis 之 $ & #?

在Ibatis中我们使用SqlMap进行Sql查询时需要引用参数,在参数引用中遇到的符号#和$之间的区分为,#可以进行与编译,进行类型匹配,而$不进行数据类型匹配,例如:

select * from table where id = #id# ,其中如果字段id为字符型,那么#id#表示的就是'id'类型,如果id为整型,那么#id#就是id类型。

select * from table where id = $id$ ,如果字段id为整型,Sql语句就不会出错,但是如果字段id为字符型,那么Sql语句应该写成 select * from table where id = '$id$'?

--------------------------------------------

实例如下:?

sql 代码

? ? update user set flag=#flag# where id in (#id#) ? ? ? ?

? ? delete from user where id in (#id#) ?

传递的id为1,2,3。但是数据却没有任何的修改。

后来查找了半天,原来原因就是这个#的问题。因为iBATIS默认会把“#”中间的变量作为字符串来处理。这样,就会出现这样的SQL?

sql 代码?

? ? update user set flag='1' where id in ('1,2,3') ? ? ? ?

? ? delete from user where id in ('1,2,3') ?

这样的SQL数据库当然是不会执行的。那我们只有绕开iBATIS了吗?

其实不用,iBATIS其实还提供了另外一种方式,那就是使用$来传递值。你使用$将你的变量括起来,iBATIS不会给这个变量做任何的处理,直接生成你要的SQL

sql 代码

? ? update user set flag=$flag$ where id in ($id$) ? ? ??

? ? update user set flag=1 ?where id in (1,2,3) ? ? ? ?

? ? delete from user where id in ($id$) ? ? ? ?

? ? delete from user where id in (1,2,3) ?

还可以用ibatis的iterate解决:

SQL:

? ? <select id="test" parameterresultclose=")" conjunction=","> ??

? ? ? ? ? ? #value[]# ??

? ? ? ? </iterate> ??

? ? </select> ?

?

? ? List list = new ArrayList(); ??

? ? list.add("aaa"); ??

? ? list.add("bbb"); ??

?

? ? List rsList = sqlMap.queryForList("roadline.test", list); ?

?

生成的sql:

? ? select * from SYS_ROAD_LINE_INFO where ROAD_LINE_NO in (?,?) ?

?

$中间的变量就是直接替换成值的

#会根据变量的类型来进行替换

比如articleTitle的类型是string, 值是"标题"的时候

$articleTitle$ = 标题

#articleTitle# = '标题'

热点排行