Can I use MyBatis to generate Dynamic SQL without executing it?
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?的更多相关文章
- MyBatis(3.2.3) - Dynamic SQL
Sometimes, static SQL queries may not be sufficient for application requirements. We may have to bui ...
- Spring mybatis源码篇章-NodeHandler实现类具体解析保存Dynamic sql节点信息
前言:通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-XMLLanguageDriver解析sql包装为SqlSource SqlNode接口类 publi ...
- mybatis Dynamic SQL
reference: http://www.mybatis.org/mybatis-3/dynamic-sql.html Dynamic SQL One of the most powerful fe ...
- Introduction to Dynamic SQL
The idea of using dynamic SQL is to execute SQL that will potentially generate and execute another S ...
- mybatis-3 Dynamic SQL
Dynamic SQL One of the most powerful features of MyBatis has always been its Dynamic SQL capabilitie ...
- ABAP动态生成经典应用之Dynamic SQL Excute 程序
[转自http://blog.csdn.net/mysingle/article/details/678598]开发说明:在SAP的系统维护过程中,有时我们需要修改一些Table中的数据,可是很多Ta ...
- [转]Dynamic SQL & Stored Procedure Usage in T-SQL
转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...
- 【mybatis深度历险系列】mybatis中的动态sql
最近一直做项目,博文很长时间没有更新了,今天抽空,学习了一下mybatis,并且总结一下.在前面的博文中,小编主要简单的介绍了mybatis中的输入和输出映射,并且通过demo简单的介绍了输入映射和输 ...
- Mybatis入门之动态sql
Mybatis入门之动态sql 通过mybatis提供的各种标签方法实现动态拼接sql. 1.if.where.sql.include标签(条件.sql片段) <sql id="sel ...
随机推荐
- EBS R12安装升级(FRESH)(五)
7.4.5 用DBUA升级 Database Upgrade Assistant提供图形界面进行升级. 将zysong.ttf复制到 /u01/oracle/TEST/db/tech_st/11.2. ...
- Hadoop DataNode不能正常工作的原因
在把Hadoop环境搭建成功,并且也Hadoop的各个组件都正常工作.在重启过几次Hadoop后发现DataNode不能正常工作,打开Hadoop 的后台http://localhost:50030和 ...
- unix下对于字符串变量的各种操作总结
在unix like系统的shell中,提供了很多操作字符串变量的灵活语法,我们接下来依次来看一看. apple@kissAir: ~$path=$PATH apple@kissAir: ~$echo ...
- JSON 在Ajax数据交换中的简单运用
随着浏览器内核更新,原先的json.js在最新的谷歌浏览下不管用了,运行报错,特此修改下代码,不使用json.js,使用Object自带的json转换方法,修改时间,2016年10月26日. 首先需要 ...
- 抛开rails使用ActiveRecord连接数据库
今天是大年三十,明天就正式进入羊年鸟,给所有程序猿(媛)同人拜个年吧!祝大家身体健康,事业有成,财源广进哦! 话归正题,以前都是在rails中使用数据库,或者在rails的console中使用:我们如 ...
- jQuery事件控制点击内容下拉
1.设计实例 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...
- WebService学习--(一)webservice相关概念
一.序言 大家或多或少都听过 WebService(Web服务),有一段时间很多计算机期刊.书籍和网站都大肆的提及和宣传WebService技术,其中不乏很多吹嘘和做广告的成 分.但是不得不承认的是W ...
- word search(二维数组中查找单词(匹配字符串))
Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...
- spring:org.springframework.web.servlet.DispatcherServlet noHandlerFound解决方法
1.搜了许久: <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern& ...
- 【JDK1.8】JUC——AbstractQueuedSynchronizer
一.前言 在上一篇中,我们对LockSupport进行了阅读,因为它是实现我们今天要分析的AbstractQueuedSynchronizer(简称AQS)的基础,重新用一下最开始的图: 可以看到,在 ...