How to execute exequte directly from java code using mybatis?

I need to execute a query that was generated by java code at runtime (not a static method). I already know how to build a dynamic query using annotation and static method or using xml mapper, but this is not suitable in my case.

Is there a way to execute a query from Java code directly?

+5
source share
3 answers

Mybatis already performs this function, but you should use the adapter as follows.

  • 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; } } 
  • create typeAlias ​​of the SQLAdapter class

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

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

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

     String _sql = "select * from table where... order by... limit..."; xxxxx.findRecords(new SQLAdapter(_sql)); 
  3. Done. You can no longer write complex sql in an XML file. Good luck.

+7
source

It seems the best answer is to use JDBC in this case.

+1
source

You can do this using an SQL query as a parameter literal:

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

You can only pass the where clause:

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

All Articles