項目中遇到的一個ibatis動態查詢

來源:互聯網
上載者:User

      網路上有大量的關於ibatis動態查詢的語句,本人在此不再狗尾續貂。只說下讓我印象很深刻的,其實是走了很大彎路的一個語句。

問題是這樣的:A 表:<br /> id<br /> content<br /> typeB 表</p><p> id,<br /> name ,B為字典表

其中A.type 就是B.Id,現在頁面需要這樣的展示內容:A.content 、A.type(實際是B.name)

這樣的展示頁面有兩個入口:

1、正常的展示頁面  sql語句 select<br /> 欄位<br /> from<br /> 表<br /> where<br /> A.type = B.id:

2、進階搜尋展示  sql語句: select<br /> 欄位<br /> from<br /> 表<br /> where<br /> A.type = B.id<br /> and<br /> A.type = ?<br /> and<br /> A.name like '%?%'

 

當做動態查詢的時候sql語句是這樣寫的:select<br /> 欄位<br /> from<br /> 表<br /> <dynamic prepend="where"><br /> <isNotNull prepend="and" property="type"><br /> type = #type#<br /> </isNotNull><br /> <isNotNull prepend="and" property="name"><br /> name like '%$name$%'<br /> </isNotNull><br /> and<br /> A.type = B.id</p><p> </dynamic><br />

期間都是更改過幾次但是在條件1或者是條件2的情況下總是會出現問題。鬱悶啊!  A.type = B.id  可是必須填寫的啊。中間還用過1=1等超級變態的用法,還是不好用。

 

 

解決後的sql語句:select<br /> 欄位<br /> from<br /> 表<br /> where<br /> A.type = B.id<br /> <dynamic prepend="and" open="(" close=")"><br /> <isNotNull prepend="and" property="type"><br /> type = #type#<br /> </isNotNull><br /> <isNotNull prepend="and" property="name"><br /> name like '%$name$%'<br /> </isNotNull><br /> </dynamic><br />

open和close的作用就是把動態語句和A.type = B.id分開,實際執行的sql如下:

select  欄位  form 表 where   A.type = B.id  and (  type = ? and  name  like  "%參數%" )。

知識很淺,不要見笑,以資鼓勵,聊以共勉!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.