5

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?

1
  • You mean, using plain JDBC? Commented Apr 22, 2013 at 20:11

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.