`

ibatis中的$和#(转)

 
阅读更多
$ 的作用实际上是字符串拼接,
select * from $tableName$
等效于
StringBuffer sb = new StringBuffer(256);
sb.append("select * from ").append(tableName);
sb.toString();

#用于变量替换
select * from table where id = #id#
等效于
prepareStement = stmt.createPrepareStement("select * from table where id = ?")
prepareStement.setString(1,'abc');

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

说道这里, 总结一下, 什么时候用$,什么时候 用 #

对于变量部分, 应当使用#, 这样可以有效的防止sql注入, 未来,# 都是用到了prepareStement,这样对效率也有一定的提升

$只是简单的字符拼接而已,对于非变量部分, 那只能使用$, 实际上, 在很多场合,$也是有很多实际意义的
例如
select * from $tableName$ 对于不同的表执行统一的查询
update $tableName$ set status = #status# 每个实体一张表,改变不用实体的状态
特别提醒一下, $只是字符串拼接, 所以要特别小心sql注入问题。
------------------------------------------------
1、用$$ 有点宏替换的意思,就是简单的字符串替换,用相应的值替换$$里的内容,如下列映射:
<select id="users" resultMap="user">select * from a $name$</select>,则在传入参数可以queryForList("users", "where name='张三'");  
2、用##则是预编译处理,传入的是什么类型就是什么类型,如下列映射:
<select id="users" resultMap="user">select * from a where a.name=#name#</select>,
你在传入参数时可以queryForList("users", "张三");则生成的sql语句是select * from a where a.name='张三'。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics