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?
解决方案
Mybatis has already this function, but you must 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 class SQLAdapter
put select tag in each object xml where you need to execute the sql directly.
${sql}
call this select method like
String _sql = "select * from table where... order by... limit...";
xxxxx.findRecords(new SQLAdapter(_sql));
Things have been all done. you can no longer writer complex sql language in the xml file. Good Luck.