Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dynamic SQL query in MyBatis with annotation(how to use selectProvider)?

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!

like image 839
ligerdave Avatar asked Jul 13 '11 21:07

ligerdave


People also ask

How do I write SQL query in MyBatis?

xml File. To define SQL mapping statement using MyBatis, we would add <select> tag in Student. xml file and inside this tag definition, we would define an "id" which will be used in mybatisRead. java file for executing SQL SELECT query on database.

How do I use Java MyBatis?

MYBATIS is a persistence framework that automates the mapping among SQL databases and objects in Java, . NET, and Ruby on Rails. MYBATIS makes it easier to build better database oriented-applications more quickly and with less code.

What is parameterType in MyBatis?

parameterType. The fully qualified class name or alias for the parameter that will be passed into this statement. This attribute is optional because MyBatis can calculate the TypeHandler to use out of the actual parameter passed to the statement. Default is unset .

How do I avoid SQL injection in MyBatis?

In general, you should consider using #{} for string substitution instead of ${} . This is because #{} causes Mybatis to create a preparedStatement which prevents SQLInjection compared to ${} which would inject unmodified string into SQL.


2 Answers

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

like image 65
farmer1992 Avatar answered Oct 13 '22 06:10

farmer1992


  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}"; 
    }
    
like image 27
acala Avatar answered Oct 13 '22 06:10

acala