2011-07-13 136 views
12

我試圖避免有一個額外的XML來定義在mybatis3映射器。註釋適合。如何在MyBatis中使用帶註釋的動態SQL查詢(如何使用selectProvider)?

我對@ SelectProvider/@ InsertProvider/etc的使用有點困惑。不要以爲網上有很多資源指導我完成這個任務。

基本上,我想在mybatis3中找到備選的註釋版本。

例如,我有一個XML映射器,我想將其轉換爲使用註解

<select ...> 
    <where> 
    <if cause.....> 
    </if> 
    <if cause......> 
    </if> 
    </where> 
</select> 

誰能提供一個具體的答案/解決方案,包括代碼?

在此先感謝!

MyClass中
@SelectProvider(type=MyClass.class, method="myMethod") 
public Object selectById(int id); 
  • 回答

    5
    1. 在你的映射器接口

      public static String myMethod() { 
          return "select * from MyTable where id=#{id}"; 
      } 
      
    15

    你的一個替代的解決方案可能是:

    在開始添加<script>你的 @annotation

    @Update("<script> 
        update Author 
        <set> 
         <if test="username != null">username=#{username},</if> 
         <if test="password != null">password=#{password},</if> 
         <if test="email != null">email=#{email},</if> 
         <if test="bio != null">bio=#{bio}</if> 
        </set> 
        where id=#{id} 
    </script>") 
    

    在額外的,我們編譯.groovy作爲對我們的項目的.class,因此,我們可以寫SQL在@annotation像上面

    +0

    這是真的很酷。但有一點需要注意:'