sochi
sochi

Reputation: 271

How to exequte query directly from java code using 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?

Upvotes: 5

Views: 8167

Answers (3)

pwojnowski
pwojnowski

Reputation: 392

You can do this using SQL query as literal parameter:

<select id="findRecords" parameterType="string" resultMap="xxxxxResultMap">  
    ${_parameter}
</select>

You can pass only where clause:

<select id="findRecords" parameterType="string" resultMap="xxxxxResultMap">  
    select * from records where ${_parameter}
</select>

Upvotes: 1

Ben
Ben

Reputation: 149

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.

Upvotes: 10

sochi
sochi

Reputation: 271

Seems like the best answer is to use JDBC in this case.

Upvotes: 2

Related Questions