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

 Mybatis中如何在SQL语句表名中使用参数

insert into prefix_${table_name} (a, b, c) values (#{a}, #{b}, #{c})

${} 表示直接使用字面量(literal value)

#{} 表示这个是个参数

如果 table_name 是 “ABC”

则 ${table_name} 是 ABC

#{table_name} 是 “ABC"

 

 

Java代码  收藏代码
  1. 1.#可以进行预编译,进行类型匹配,#变量名# 会转化为 jdbc 的 类型  
  2.    $不进行数据类型匹配,$变量名$就直接把 $name$替换为 name的内容  
  3.    例如:  
  4.      select * from tablename where id = #id# ,假设id的值为12,其中如果数据库字段id为字符型,那么#id#表示的就是'12',如果id为整型,那么#id#就是 12  
  5.     会转化为jdbc的 select * from tablename where id=?,把?参数设置为id的值  
  6.      select * from tablename where id = $id$ ,如果字段id为整型,Sql语句就不会出错,但是如果字段id为字符型,  
  7.      那么Sql语句应该写成 select * from table where id = '$id$'  
  8.       
  9. 3.#方式能够很大程度防止sql注入.  
  10. 4.$方式无法防止sql注入.  
  11. 5.$方式一般用于传入数据库对象.例如传入表名.  
  12. 6.所以ibatis用#比$好,一般能用#的就别用$.  
  13. 另外,使用##可以指定参数对应数据库的类型  
  14. 如:  
  15. select * from tablename where id = #id:number#   
  16.    
  17. 在做in,like 操作时候要特别注意  
  18.   
  19.   
  20. 总结以下:  
  21. $号使用在具体pojo类也就是非基本类型的取值,而#号使用在具体有基本类型的取值  
  22. <sql id="Update_By_Example_Where_Clause">  
  23.     <where>  
  24.       <foreach collection="example.oredCriteria" item="criteria" separator="or">  
  25.         <if test="criteria.valid">  
  26.           <trim prefix="(" prefixOverrides="and" suffix=")">  
  27.             <foreach collection="criteria.criteria" item="criterion">  
  28.               <choose>  
  29.                  <when test="criterion.noValue">  
  30.                    and ${criterion.condition}  
  31.                  </when>  
  32.                  <when test="criterion.singleValue">  
  33.                    and ${criterion.condition} #{criterion.value}  
  34.                  </when>  
  35.                  <when test="criterion.betweenValue">  
  36.                    and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  
  37.                  </when>  
  38.                  <when test="criterion.listValue">  
  39.                    and ${criterion.condition}  
  40.                     <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">  
  41.                      #{listItem}  
  42.                     </foreach>  
  43.                 </when>  
  44.               </choose>  
  45.             </foreach>  
  46.           </trim>  
  47.         </if>  
  48.       </foreach>  
  49.     </where>  
  50.   </sql> 
posted @ 2015-09-04 23:44  yunlvrensheng  阅读(679)  评论(0编辑  收藏  举报