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:

  1. name login
  2. ----- -----
  3. Andy a
  4. Barry b
  5. Cris c

User class:

  1. package pack.test;
  2. public class User {
  3. private String name;
  4. private String login;
  5. // getters and setters ommited
  6. }

UserService interface:

  1. package pack.test;
  2. public interface UserService {
  3. // using a different sort of parameter to show some dynamic SQL
  4. public User getUser(int loginNumber);
  5. }

UserService.xml mapper file:

  1. <mapper namespace="pack.test.UserService">
  2. <select id="getUser" resultType="pack.test.User" parameterType="int">
  3. <!-- dynamic change of parameter from int index to login string -->
  4. select * from user where login = <choose>
  5. <when test="_parameter == 1">'a'</when>
  6. <when test="_parameter == 2">'b'</when>
  7. <otherwise>'c'</otherwise>
  8. </choose>
  9. </select>
  10. </mapper>

sqlmap-config.file:

  1. <configuration>
  2. <settings>
  3. <setting name="lazyLoadingEnabled" value="false" />
  4. </settings>
  5. <environments default="development">
  6. <environment id="development">
  7. <transactionManager type="JDBC"/>
  8. <dataSource type="POOLED">
  9. <property name="driver" value="com.mysql.jdbc.Driver"/>
  10. <property name="url" value="jdbc:mysql://localhost/test"/>
  11. <property name="username" value="..."/>
  12. <property name="password" value="..."/>
  13. </dataSource>
  14. </environment>
  15. </environments>
  16. <mappers>
  17. <mapper resource="pack/test/UserService.xml"/>
  18. </mappers>
  19. </configuration>

AppTester to show the result:

  1. package pack.test;
  2. import java.io.Reader;
  3. import org.apache.ibatis.io.Resources;
  4. import org.apache.ibatis.mapping.BoundSql;
  5. import org.apache.ibatis.mapping.MappedStatement;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. public class AppTester {
  9. private static String CONFIGURATION_FILE = "sqlmap-config.xml";
  10. public static void main(String[] args) throws Exception {
  11. Reader reader = null;
  12. SqlSession session = null;
  13. try {
  14. reader = Resources.getResourceAsReader(CONFIGURATION_FILE);
  15. session = new SqlSessionFactoryBuilder().build(reader).openSession();
  16. UserService userService = session.getMapper(UserService.class);
  17. // three users retreived from index
  18. for (int i = 1; i <= 3; i++) {
  19. User user = userService.getUser(i);
  20. System.out.println("Retreived user: " + user.getName() + " " + user.getLogin());
  21. // must mimic the internal statement key for the mapper and method you are calling
  22. MappedStatement ms = session.getConfiguration().getMappedStatement(UserService.class.getName() + ".getUser");
  23. BoundSql boundSql = ms.getBoundSql(i); // parameter for the SQL statement
  24. System.out.println("SQL used: " + boundSql.getSql());
  25. System.out.println();
  26. }
  27. } finally {
  28. if (reader != null) {
  29. reader.close();
  30. }
  31. if (session != null) {
  32. session.close();
  33. }
  34. }
  35. }
  36. }

And the result:

  1. Retreived user: Andy a
  2. SQL used: select * from user where login = 'a'
  3. Retreived user: Barry b
  4. SQL used: select * from user where login = 'b'
  5. Retreived user: Cris c
  6. SQL used: select * from user where login = 'c'

http://stackoverflow.com/questions/13195144/can-i-use-mybatis-to-generate-dynamic-sql-without-executing-it

https://my.oschina.net/lichhao/blog/114311

Can I use MyBatis to generate Dynamic SQL without executing it?的更多相关文章

  1. MyBatis(3.2.3) - Dynamic SQL

    Sometimes, static SQL queries may not be sufficient for application requirements. We may have to bui ...

  2. Spring mybatis源码篇章-NodeHandler实现类具体解析保存Dynamic sql节点信息

    前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource SqlNode接口类 publi ...

  3. mybatis Dynamic SQL

    reference: http://www.mybatis.org/mybatis-3/dynamic-sql.html Dynamic SQL One of the most powerful fe ...

  4. Introduction to Dynamic SQL

    The idea of using dynamic SQL is to execute SQL that will potentially generate and execute another S ...

  5. mybatis-3 Dynamic SQL

    Dynamic SQL One of the most powerful features of MyBatis has always been its Dynamic SQL capabilitie ...

  6. ABAP动态生成经典应用之Dynamic SQL Excute 程序

    [转自http://blog.csdn.net/mysingle/article/details/678598]开发说明:在SAP的系统维护过程中,有时我们需要修改一些Table中的数据,可是很多Ta ...

  7. [转]Dynamic SQL & Stored Procedure Usage in T-SQL

    转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...

  8. 【mybatis深度历险系列】mybatis中的动态sql

    最近一直做项目,博文很长时间没有更新了,今天抽空,学习了一下mybatis,并且总结一下.在前面的博文中,小编主要简单的介绍了mybatis中的输入和输出映射,并且通过demo简单的介绍了输入映射和输 ...

  9. Mybatis入门之动态sql

    Mybatis入门之动态sql 通过mybatis提供的各种标签方法实现动态拼接sql. 1.if.where.sql.include标签(条件.sql片段) <sql id="sel ...

随机推荐

  1. EBS R12安装升级(FRESH)(五)

    7.4.5 用DBUA升级 Database Upgrade Assistant提供图形界面进行升级. 将zysong.ttf复制到 /u01/oracle/TEST/db/tech_st/11.2. ...

  2. Hadoop DataNode不能正常工作的原因

    在把Hadoop环境搭建成功,并且也Hadoop的各个组件都正常工作.在重启过几次Hadoop后发现DataNode不能正常工作,打开Hadoop 的后台http://localhost:50030和 ...

  3. unix下对于字符串变量的各种操作总结

    在unix like系统的shell中,提供了很多操作字符串变量的灵活语法,我们接下来依次来看一看. apple@kissAir: ~$path=$PATH apple@kissAir: ~$echo ...

  4. JSON 在Ajax数据交换中的简单运用

    随着浏览器内核更新,原先的json.js在最新的谷歌浏览下不管用了,运行报错,特此修改下代码,不使用json.js,使用Object自带的json转换方法,修改时间,2016年10月26日. 首先需要 ...

  5. 抛开rails使用ActiveRecord连接数据库

    今天是大年三十,明天就正式进入羊年鸟,给所有程序猿(媛)同人拜个年吧!祝大家身体健康,事业有成,财源广进哦! 话归正题,以前都是在rails中使用数据库,或者在rails的console中使用:我们如 ...

  6. jQuery事件控制点击内容下拉

    1.设计实例 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

  7. WebService学习--(一)webservice相关概念

    一.序言 大家或多或少都听过 WebService(Web服务),有一段时间很多计算机期刊.书籍和网站都大肆的提及和宣传WebService技术,其中不乏很多吹嘘和做广告的成 分.但是不得不承认的是W ...

  8. word search(二维数组中查找单词(匹配字符串))

    Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...

  9. spring:org.springframework.web.servlet.DispatcherServlet noHandlerFound解决方法

    1.搜了许久: <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern& ...

  10. 【JDK1.8】JUC——AbstractQueuedSynchronizer

    一.前言 在上一篇中,我们对LockSupport进行了阅读,因为它是实现我们今天要分析的AbstractQueuedSynchronizer(简称AQS)的基础,重新用一下最开始的图: 可以看到,在 ...