`
小杨学JAVA
  • 浏览: 886472 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

关于ibatis动态查询的语句(转载)

 
阅读更多

  网络上有大量的关于ibatis动态查询的语句,本人在此不再狗尾续貂。只说下让我印象很深刻的,其实是走了很大弯路的一个语句。

问题是这样的:

  1. A  表:  
  2.   id  
  3.   content  
  4.   type  
  1. B 表  
  2.   
  3.   id,  
  4.   name  
,B为字典表

 

其中A.type 就是B.Id,现在页面需要这样的展示内容:A.content 、A.type(实际是B.name)

这样的展示页面有两个入口:

1、正常的展示页面  sql语句

  1. select  
  2.       字段  
  3.   from    
  4.       表  
  5.   where   
  6.      A.type = B.id  

 

2、高级搜索展示  sql语句:

  1. select  
  2.       字段  
  3.   from    
  4.       表  
  5.   where   
  6.       A.type = B.id  
  7.     and  
  8.       A.type = ?  
  9.     and  
  10.       A.name like '%?%'  

 

 

当做动态查询的时候sql语句是这样写的:

  1. select  
  2.        字段  
  3.    from    
  4.        表  
  5.    <dynamic prepend="where">  
  6.      <isNotNull prepend="and" property="type">  
  7.         type = #type#  
  8.      </isNotNull>  
  9.       <isNotNull prepend="and" property="name">  
  10.         name like '%$name$%'  
  11.      </isNotNull>  
  12.      and  
  13.         A.type = B.id  
  14.   
  15.   </dynamic>  
  16.     

 

期间都是更改过几次但是在条件1或者是条件2的情况下总是会出现问题。郁闷啊!  A.type = B.id  可是必须填写的啊。中间还用过1=1等超级变态的用法,还是不好用。

 

 

解决后的sql语句:

  1. select  
  2.        字段  
  3.    from    
  4.        表  
  5.    where  
  6.      A.type = B.id  
  7.    <dynamic prepend="and" open="(" close=")">  
  8.      <isNotNull prepend="and" property="type">  
  9.         type = #type#  
  10.      </isNotNull>  
  11.       <isNotNull prepend="and" property="name">  
  12.         name like '%$name$%'  
  13.      </isNotNull>  
  14.    </dynamic>  

 

open和close的作用就是把动态语句和A.type = B.id分开,实际执行的sql如下:

select  字段  form 表 where   A.type = B.id  and (  type = ? and  name  like  "%参数%" )。

知识很浅,不要见笑,以资鼓励,聊以共勉!

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics