Although MyBatis was designed to execute the query after it builds it, you can make use of it's configuration and a little bit of "inside knowledge" to get to what you need.
MyBatis is a very nice framework, unfortunately it lacks on the documentations side so the source code is you friend. If you dig around you should bump into these classes: org.apache.ibatis.mapping.MappedStatement
and org.apache.ibatis.mapping.BoundSql
which are key players into building the dynamic SQL. Here is a basic usage example:
MySQL table user
with this data in it:
name login
----------AndyBarryCris c
User
class:
package.test;publicclassUser{privateString;privateString;// getters and setters ommited}
UserService
interface:
package.test;publicinterfaceUserService{// using a different sort of parameter to show some dynamic SQLpublicUser(int);}
UserService.xml
mapper file:
<mapper namespace="pack.test.UserService"><select id="getUser"="pack.test.User"="int"><!--int-->*=<choose><when test="_parameter == 1">'a'</when><when test="_parameter == 2">'b'</when><otherwise>'c'</otherwise></choose></select></mapper>
sqlmap-config.file
:
<configuration><settings><setting name="lazyLoadingEnabled"="false"/></settings><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver"="com.mysql.jdbc.Driver"/><property name="url"="jdbc:mysql://localhost/test"/><property name="username"="..."/><property name="password"="..."/></dataSource></environment></environments><mappers><mapper resource="pack/test/UserService.xml"/></mappers></configuration>
AppTester
to show the result:
package.test;import.io.Reader;import.apache.ibatis.io.Resources;import.apache.ibatis.mapping.BoundSql;import.apache.ibatis.mapping.MappedStatement;import.apache.ibatis.session.SqlSession;import.apache.ibatis.session.SqlSessionFactoryBuilder;publicclassAppTester{privatestaticString="sqlmap-config.xml";publicstaticvoid(String[])throwsException{Reader=null;SqlSession=null;try{=Resources.getResourceAsReader(CONFIGURATION_FILE);=newSqlSessionFactoryBuilder().build(reader).openSession();UserService=.getMapper(UserService.class);// three users retreived from indexfor(int=1;<=3;++){User=.getUser(i);System.out.println("Retreived user: "+.getName()+" "+.getLogin());// must mimic the internal statement key for the mapper and method you are callingMappedStatement=.getConfiguration().getMappedStatement(UserService.class.getName()+".getUser");BoundSql=