[转]ibatis中井号跟美元符号区别(#、$)
2015-09-04 23:44
489 查看
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代码
![](https://oscdn.geek-share.com/Uploads/Images/Content/201909/23/137e9fbb4ea98564c59e79bbec4cdd2d.png)
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类也就是非基本类型的取值,而#号使用在具体有基本类型的取值
<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>
相关文章推荐
- 微博开发笔记上(未完待续)
- SGU 194. Reactor Cooling【无源汇上下界最大流】
- C#之Attribute(特性)
- Atitit. 衡量项目规模 ----包含的类的数量 .net java类库包含多少类 多少个api方法??
- Common Lisp 学习笔记(1)
- 排序算法总结
- Atitit. 衡量项目规模 ----包含的类的数量 .net java类库包含多少类 多少个api方法??
- Atitit. 衡量项目规模 ----包含的类的数量 .net java类库包含多少类 多少个api方法??
- 文本编辑工具vim的使用方法练习
- iOS开发-用ZipArchive添加和解压zip包
- apache+tomcat反向代理
- mysql SQL Select 语句 简单应用
- GraphX的基本介绍
- VS2015+OpenCV3.0配置教程
- 杭电OJ-2093_考试排名
- 简单文本函数
- vncserver的自动启动及vncserver桌面的自动准备
- Xcode默认快捷键太别扭,一招教你制服它!
- poj 3624
- 程序包管理之rpm/yum/编译