`
wenjie12201
  • 浏览: 148310 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论
  • luoxun11: 其实这个问题的本质是用##包围变量的时候ibatis会采用St ...
    iBATIS #和$

iBATIS #和$

阅读更多

比如:

sql 代码
 
  1. select * from member where id =#id#  



然后,我们会在程序中给id这个变量传递一个值,iBATIS会自动将#id#转成我们传递的内容。

但是我最近碰到一个奇怪的问题。我在批量删除或修改的时候,居然SQL失效了。

SQL如下:

sql 代码
 
  1. update user set flag=#flag# where id in (#id#)  
  2.   
  3. delete from user where id in (#id#)  



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

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

sql 代码
 
  1. update user set flag='1' where id in ('1,2,3')  
  2.   
  3. delete from user where id in ('1,2,3')  



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

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

sql 代码
 
  1. update user set flag=$flag$ where id in ($id$)  
  2.   
  3. update user set flag=1  where id in (1,2,3)  
  4.   
  5. delete from user where id in ($id$)  
  6.   
  7. delete from user where id in (1,2,3)  

 

 

ibatis取sequence值

 <select id="getNextValue" parameterClass="java.lang.String" resultClass="java.lang.Long">
      select SEQ_$seqName$.NEXTVAL from dual
 </select>

 

  public Long getNextValue(String seqName) {
      return (Long) sqlMapClientTemplate.queryForObject("base.getNextValue",seqName);
 }

分享到:
评论
1 楼 luoxun11 2012-09-26  
其实这个问题的本质是用##包围变量的时候ibatis会采用Statement对象对sql语句进行拼接自然会采用将变量转化为字符串的形式,而用$$包围变量的时候会使用PreparedStatement预置语句的形式将变量设置为等价的sql值

相关推荐

Global site tag (gtag.js) - Google Analytics