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
----- -----
Andy a
Barry b
Cris c

User class:

package pack.test;
public class User {
private String name;
private String login;
// getters and setters ommited
}

UserService interface:

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

UserService.xml mapper file:

<mapper namespace="pack.test.UserService">
<select id="getUser" resultType="pack.test.User" parameterType="int">
<!-- dynamic change of parameter from int index to login string -->
select * from user where login = <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" value="false" />
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/test"/>
<property name="username" value="..."/>
<property name="password" value="..."/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="pack/test/UserService.xml"/>
</mappers>
</configuration>

AppTester to show the result:

package pack.test;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class AppTester {
private static String CONFIGURATION_FILE = "sqlmap-config.xml"; public static void main(String[] args) throws Exception {
Reader reader = null;
SqlSession session = null;
try { reader = Resources.getResourceAsReader(CONFIGURATION_FILE);
session = new SqlSessionFactoryBuilder().build(reader).openSession();
UserService userService = session.getMapper(UserService.class); // three users retreived from index
for (int i = 1; i <= 3; i++) {
User user = userService.getUser(i);
System.out.println("Retreived user: " + user.getName() + " " + user.getLogin()); // must mimic the internal statement key for the mapper and method you are calling
MappedStatement ms = session.getConfiguration().getMappedStatement(UserService.class.getName() + ".getUser");
BoundSql boundSql = ms.getBoundSql(i); // parameter for the SQL statement
System.out.println("SQL used: " + boundSql.getSql());
System.out.println();
} } finally {
if (reader != null) {
reader.close();
}
if (session != null) {
session.close();
}
}
}
}

And the result:

Retreived user: Andy a
SQL used: select * from user where login = 'a' Retreived user: Barry b
SQL used: select * from user where login = 'b' Retreived user: Cris c
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. Linux磁盘 - fdisk,partprobe, mkfs, mke2fs, fsck, badblocks, mount, mknod

    磁盘分区: fdisk [root@www ~]# fdisk [-l] 装置名称 选项与参数: -l :输出后面接的装置所有的 partition 内容.若仅有 fdisk -l 时, 则系统将会把 ...

  2. css选择器语法速查

    通用选择器 *{} 类似于通配符,匹配文档中所有元素类型: 类型选择器 h1,h2,p{} 匹配以逗号隔开元素列表中的所有元素 类选择器 .glass{} or p.glass{} id选择器 #id ...

  3. 关于Mac中PATH环境变量可能会被修改的几个地方

    一个是全局的profile文件,位置在/etc/profile中:另一个和用户无关的全局位置在/etc/paths.d目录中: apple@kissAir: paths.d$pwd /etc/path ...

  4. python socketserver框架解析

    socketserver框架是一个基本的socket服务器端框架, 使用了threading来处理多个客户端的连接, 使用seletor模块来处理高并发访问, 是值得一看的python 标准库的源码之 ...

  5. PM2 Quick Start

    PM2教程 @(Node)[负载均衡|进程管理器] [TOC] PM2简介 PM2 是一个带有负载均衡功能的Node应用的进程管理器. 当你要把你的独立代码利用全部的服务器上的所有CPU,并保证进程永 ...

  6. java日期操作常用工具

    java日期操作常用工具 package com..util; import java.sql.Timestamp; import java.text.SimpleDateFormat; import ...

  7. oracle面试题目总结

    阿里巴巴公司DBA笔试题  http://searchdatabase.techtarget.com.cn/tips/2/2535002.shtml   注:以下题目,可根据自己情况挑选题目作答,不必 ...

  8. IntelliJ IDEA下Cannot resolve symbol XXX的解决方法

    Idea导入maven项目后,运行能通过,但是打开一些类后,会出现Cannot resolve symbol XXX的错误提示. 考虑几种可能: 1.JDK版本,设置JDK和Maven的JDK版本. ...

  9. CAN数据格式-ASC

    Vector工具录制的数据,一般有ASC和BLF两种格式,本文介绍ASC. 1. ASC定义 ASC(ASCII)即文本文件,数据已可视化的文本存储. 2.ASC查看 通常情况下,用记事本就可以打开. ...

  10. 窗口函数解决数据岛问题(mysql暂无窗口函数,可以通过用户变量解决窗口函数问题)

    数据岛问题: 有表: create table dataisland (id int)  insert into  dataisland values(1),(2),(3),(7),(11),(12) ...