Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exequte query directly from java code using mybatis?

Tags:

java

sql

mybatis

I need to execute query which has been generated by java code in runtime (not static method). I already know how to build dynamic query by using annotation and static method or using xml mapper, but it is not suitable in my case.

Is there any way to execute query from java code directly?

like image 288
sochi Avatar asked Apr 22 '13 16:04

sochi


1 Answers

Mybatis has already this function, but you must use the adapter as follows.

  1. create an adapter class;

    public class SQLAdapter {
      String sql;
    
      public SQLAdapter(String sql) {
          this.sql = sql;
      }
    
      public String getSql() {
          return sql;
      }
    
      public void setSql(String sql) {
          this.sql = sql;
      }
    }
    
  2. create typeAlias of class SQLAdapter

<typeAlias alias="sqladapter" type="com.zj.xxx.xxx.SQLAdapter" />

  1. put select tag in each object xml where you need to execute the sql directly.

    <select id="findRecords" parameterType="SQLAdapter" resultMap="xxxxxResultMap">  
        ${sql}  
    </select> 
    
  2. call this select method like

    String _sql = "select * from table where... order by... limit...";
    xxxxx.findRecords(new SQLAdapter(_sql));
    
  3. Things have been all done. you can no longer writer complex sql language in the xml file. Good Luck.

like image 178
Ben Avatar answered Oct 29 '22 03:10

Ben