Can I use MyBatis to generate Dynamic SQL without executing it?
2017-04-07 19:59
525 查看
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:
MySQL table
And the result:
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.MappedStatementand
org.apache.ibatis.mapping.BoundSqlwhich are key players into building the dynamic SQL. Here is a basic usage example:
MySQL table
userwith this data in it:
name login ----- ----- Andy a Barry b Cris c
Userclass:
package pack.test; public class User { private String name; private String login; // getters and setters ommited }
UserServiceinterface:
package pack.test; public interface UserService { // using a different sort of parameter to show some dynamic SQL public User getUser(int loginNumber); }
UserService.xmlmapper 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>
AppTesterto 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
相关文章推荐
- Question[SQL]:Can you use a SQL statement to calculating it!
- Can't believe it takes me so long to do a so easy thing in sql
- How To Use Dynamic Sql in Sql Server ?
- asm[dynamically produce a class and use it without writing it to disk]
- How To Use Dynamic Sql in Sql Server ?
- Question[SQL]:Can you use a SQL statement to finding duplicate values!
- 053-7 When executing a SQL workload, you choose to generate execution plans only, without collecting
- This function has none of Deterministic,no sql,or reads sql data in its declaration and binary logging is enabled(you *might* want to use the less safe log_bin_trust_function_creators variable
- Generating user instances in Sql Server is disabled. Use sp_configure 'user instances enabled' to generate user instances
- use dynamic sql to output the result
- 关于Generating user instances in SQL Server is disabled. Use sp_configure 'user instances enabled' to generate user instances的错误
- 关于Generating user instances in SQL Server is disabled. Use sp_configure 'user instances enabled' to generate user instances的错误
- ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings
- How to execute an OS command in SQL*PLUS without leaving the session ?
- create sqlserver login user and add it to certain db user (sqlserver authentication)
- Pods written in Swift can only be integrated as frameworks; add `use_frameworks!` to your Podfile or
- Colored SQL--How to force the AWR to capture a specified SQL even if it is not the top one
- Chinese version QQ—how to install it and use it to make a audio call and video call
- It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level
- 【IBM-WALA】Step by Step : use WALA to generate System Dependency Graph PDF and Dot File (Mac)