Reputation: 271
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
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
Reputation: 149
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
<typeAlias alias="sqladapter" type="com.zj.xxx.xxx.SQLAdapter" />
put select tag in each object xml where you need to execute the sql directly.
<select id="findRecords" parameterType="SQLAdapter" resultMap="xxxxxResultMap">
${sql}
</select>
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.
Upvotes: 10