18

I am trying to avoid having an additional xml to define the mapper in mybatis3. Annotation fits right in.

I am a bit confused by the usage of @SelectProvider/@InsertProvider/etc. Don't think there are many resources online guiding me through this.

Basically, I will like to find the annotation version of alternative for in mybatis3.

For example, I have a xml mapper and I wanna convert it to use annotation

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

Could anyone provide a concrete answer/solution including the code?

Thanks in advance!

Andrew Reid
  • 37,021
  • 7
  • 64
  • 83
ligerdave
  • 714
  • 2
  • 6
  • 13

2 Answers2

27

An alternative solution for you could be:

Add <script> at the beginning of your @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>")

In additional, we compile .groovy to .class in our projects, thus, we can write SQL in @annotation like above

thermz
  • 2,386
  • 3
  • 20
  • 28
farmer1992
  • 7,816
  • 3
  • 30
  • 26
  • This is really cool. One caveat though: the ` – LordOfThePigs Mar 25 '14 at 21:11
  • 1
    @Phate 3.2+ https://github.com/mybatis/mybatis-3/blob/mybatis-3.2.0/src/main/java/org/apache/ibatis/scripting/xmltags/XMLLanguageDriver.java – farmer1992 May 27 '15 at 08:56
10
  1. in your mapper interface:

    @SelectProvider(type=MyClass.class, method="myMethod")
    public Object selectById(int id);
    
  2. in MyClass:

    public static String myMethod() {
        return "select * from MyTable where id=#{id}"; 
    }
    
acala
  • 332
  • 3
  • 11