ibatis中井号跟美元符号区别(#、$)

时间:2022-09-23 14:37:15

http://my.oschina.net/zimingforever/blog/98190

原文出处 http://jsczxy2.iteye.com/blog/1218679

1、#可以进行预编译,进行类型匹配,#变量名#  会转化为 jdbc 的 类型
    $不进行数据类型匹配,$变量名$就直接把 $name$替换为 name的内容
    例如:
     select * from tablename where id = #id# ,假设id的值为12,其中如果数据库字段id为字符型,那么#id#表示的就是'12',如果id为整型,那么#id#就是 12
    会转化为jdbc的 select * from tablename where id=?,把?参数设置为id的值
     select * from tablename where id = $id$ ,如果字段id为整型,Sql语句就不会出错,但是如果字段id为字符型,
     那么Sql语句应该写成 select * from table where id = '$id$'
    
3、#方式能够很大程度防止sql注入.
4、$方式无法方式sql注入.
5、$方式一般用于传入数据库对象.例如传入表名.
6、所以ibatis用#比$好,一般能用#的就别用$.
另外,使用##可以指定参数对应数据库的类型
如:
select * from tablename where id = #id:number# 
 
在做in,like 操作时候要特别注意

总结以下:
$号使用在具体pojo类也就是非基本类型的取值,而#号使用在具体有基本类型的取值

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
< sql id = "Update_By_Example_Where_Clause" >
     < where >
       < foreach collection = "example.oredCriteria" item = "criteria" separator = "or" >
         < if test = "criteria.valid" >
           < trim prefix = "(" prefixOverrides = "and" suffix = ")" >
             < foreach collection = "criteria.criteria" item = "criterion" >
               < choose >
                 < when test = "criterion.noValue" >
                   and ${criterion.condition}
                 </ when >
                 < when test = "criterion.singleValue" >
                   and ${criterion.condition} #{criterion.value}
                 </ when >
                 < when test = "criterion.betweenValue" >
                   and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                 </ when >
                 < when test = "criterion.listValue" >
                   and ${criterion.condition}
                   < foreach close = ")" collection = "criterion.value" item = "listItem" open = "(" separator = "," >
                     #{listItem}
                   </ foreach >
                 </ when >
               </ choose >
             </ foreach >
           </ trim >
         </ if >
       </ foreach >
     </ where >
   </ sql >