如何在带有注释的MyBatis中使用动态SQL查询(如何使用selectProvider)?

lig*_*ave 17 mapping orm annotations mybatis

我试图避免使用额外的xml来定义mybatis3中的映射器.注释适合于.

我对@ SelectProvider/@ InsertProvider /等的使用感到有点困惑.不要以为网上有很多资源可以指导我完成这项工作.

基本上,我想在mybatis3中找到替代的注释版本.

例如,我有一个xml映射器,我想将其转换为使用注释

<select ...>
  <where>
    <if cause.....>
    </if>
    <if cause......>
    </if>
  </where>
</select>
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供包含代码的具体答案/解决方案吗?

提前致谢!

far*_*992 22

替代解决方案可能是:

<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>")
Run Code Online (Sandbox Code Playgroud)

另外,我们在项目中将.groovy编译为.class,因此,我们可以像上面那样在@annotation中编写SQL


aca*_*ala 8

  1. 在mapper界面中:

    @SelectProvider(type=MyClass.class, method="myMethod")
    public Object selectById(int id);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在MyClass中:

    public static String myMethod() {
        return "select * from MyTable where id=#{id}"; 
    }
    
    Run Code Online (Sandbox Code Playgroud)