- 浏览: 3419 次
- 性别:
- 来自: 郑州
文章分类
最新评论
-
Vity:
<div class="quote_title ...
SQL 语句组装类 (JAVA 实现) -
xiaokang1582830:
有什么实质性的意义?
SQL 语句组装类 (JAVA 实现)
自己某事写了个SQL组装工具类
支持普通条件、日期条件(Oracle和Mysql)。
支持比较运算,like查询,in查询,not in 查询。
支持分组,排序。
代码如下:
使用spring jdbc 的时候组装sql
支持普通条件、日期条件(Oracle和Mysql)。
支持比较运算,like查询,in查询,not in 查询。
支持分组,排序。
代码如下:
package cn.create.cbl.core.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang3.StringUtils; import cn.create.cbl.core.exception.AppException; import cn.create.cbl.core.global.Constants; import cn.create.cbl.core.global.ResultCode; public class SQLQueryUtil extends BaseUtil { private static final long serialVersionUID = -4008847394285279230L; private static String USE_JDBC_DRIVER = Constants.getConfig("jdbc.driverClassName"); /** * main() * * @param args */ public static void main(String[] args) { SQLQueryUtil util = new SQLQueryUtil(); util.addTable("base_user"); util.addTable("base_group"); util.addColumn("user_name"); util.addColumn("user_age"); util.addAndCondition("id", RelationalOperators.EQ, "xxxx", ValueType.STRING); util.addAndInCondition("user_age", "'x','x','x','x','x'"); util.addOrLikeCondition("xxx", "yyyy"); util.addGroupBy("user_name"); util.addAscOrderBy("create_time"); util.addDescOrderBy("id"); System.out.println(util.toSQL()); } /** * 日期格式化字符串 如:2013-06-20 */ public static final String FMT_DATE = "yyyy-MM-dd"; /** * 时间格式化字符串 如:13:01:01 */ public static final String FMT_TIME = "HH:mm:ss"; /** * 日期时间格式化字符串 如:2013-06-20 13:01:01 */ public static final String FMT_DATETIME = "yyyy-MM-dd HH:mm:ss"; /** * 逻辑运算 * * @author Vity * */ public enum LogicalOperators { AND("AND"), OR("OR"); private String value; private LogicalOperators(String value) { this.value = value; } public String toString() { return new String(this.value); } } /** * 关系运算 * * <p> * EQ("="), NE("<>"), GT(">"), GE(">="), LT("<"), LE("<=") * </p> * * @author Vity * */ public enum RelationalOperators { EQ("="), NE("<>"), GT(">"), GE(">="), LT("<"), LE("<="); private String value; private RelationalOperators(String value) { this.value = value; } public String toString() { return this.value; } } /** * 排序方式 * * @author Vity * */ public enum SortMethod { ASC("ASC"), DESC("DESC"); private String value; private SortMethod(String value) { this.value = value; } public String toString() { return this.value; } } /** * 值类型 * * @author Vity * */ public enum ValueType { NUMBER, DATE, STRING, TIME, DATETIME } /** * 内置表别名前缀 */ private final String TABLE_ALIAS_NAME = "TEMP_TABLE_ALIAS_"; /** * 内置表别名索引 */ private int TABLE_ALIAS_INDEX = 0; /** * 是否调试模式 非调试模式则不打印SQL语句 */ private boolean isDebug = true; /** * 是否去重 */ private boolean isDistinct = false; /** * 表名及别名集合 key : table & view name | value : alias name * <p> * <b>注意:</b>目前不支持重复表查询 * </p> */ private Map<String, String> tableMap = new HashMap<String, String>(); /** * 待查列名集合 key : column name value : | alias name */ private Map<String, String> columnMap = new HashMap<String, String>(); /** * 查询条件集合 key : and & or | value 条件值 */ private Map<String, String> conditionMap = new IdentityHashMap<String, String>(); /** * 排序条件集合 */ private Map<String, String> orderMap = new HashMap<String, String>(); /** * 分组集合 */ private List<String> groupList = new ArrayList<String>(); /** * sql生成结果 */ private StringBuilder sqlResult = new StringBuilder(); /** * 追加字符串,在后面添加一个空格 * * @param string * @return */ private SQLQueryUtil append(String string) { sqlResult.append(string).append(" "); return this; } /** * 删除最后两位字符串 * * @return */ private SQLQueryUtil clearEndChar() { sqlResult.delete(sqlResult.length() - 2, sqlResult.length()); return this; } /** * 生成SQL语句 * * @return */ public String toSQL() { if (tableMap.isEmpty()) { throw new AppException(ResultCode.Failure, "未发现表或视图"); } this.append("SELECT"); if (isDistinct) { this.append("DISTINCT"); } if (columnMap.isEmpty()) { this.append("*"); } else { for (String key : columnMap.keySet()) { this.append(key); if (!StringUtils.isBlank(columnMap.get(key))) { this.append("AS").append(columnMap.get(key)); } this.append(","); } this.clearEndChar(); } this.append("FROM"); for (String key : tableMap.keySet()) { this.append(key); if (!StringUtils.isBlank(tableMap.get(key))) { this.append("AS").append(tableMap.get(key)); } this.append(","); } this.clearEndChar().append(" "); if (!groupList.isEmpty()) { this.append("GROUP BY"); for (String field : groupList) { this.append(field).append(","); } this.clearEndChar(); } if (!conditionMap.isEmpty()) { if (!groupList.isEmpty()) { this.append("HAVING"); } else { this.append("WHERE"); } this.append("1 = 1"); for (Entry<String, String> entry : conditionMap.entrySet()) { this.append(entry.getKey()).append(entry.getValue()); } } if (!orderMap.isEmpty()) { this.append("ORDER BY"); for (String key : orderMap.keySet()) { this.append(key).append(orderMap.get(key)).append(","); } this.clearEndChar(); } if (isDebug) { logger.trace(sqlResult.toString().replace(" ,", ",").replace(" ", " ").replace(" 1 = 1 AND", "").replace(" 1 = 1 OR", "")); } return sqlResult.toString().replace(" ,", ",").replace(" ", " ").replace(" 1 = 1 AND", "").replace(" 1 = 1 OR", ""); } /** * 设置 是否Distinct查询 * * @param isDistinct */ public void setDistinct(boolean isDistinct) { this.isDistinct = isDistinct; } /** * 添加待查询的表或视图名称 * * @param tableName * @return */ public SQLQueryUtil addTable(String tableName) { tableMap.put(tableName, TABLE_ALIAS_NAME + TABLE_ALIAS_INDEX++); return this; } /** * 添加待查询的表或视图名称,并指定别名 * * @param tableName * @param aliasName * @return */ public SQLQueryUtil addTable(String tableName, String aliasName) { if (aliasName.contains(TABLE_ALIAS_NAME)) { throw new AppException(ResultCode.Failure, "不能使用这个别名前缀:" + TABLE_ALIAS_NAME); } tableMap.put(tableName, aliasName); return this; } /** * 添加待查列 * * @param columnName * @return */ public SQLQueryUtil addColumn(String columnName) { return this.addColumn(columnName, ""); } /** * 添加待查列,并指定别名 * * @param columnName * @param aliasName * @return */ public SQLQueryUtil addColumn(String columnName, String aliasName) { columnMap.put(columnName, aliasName); return this; } /** * 添加查询条件 * * <p> * <span>针对日期类型查询的说明</span> <div> * 日期查询必须将查询值按照本类提供的格式化字符串进行格式化,并指定相应的ValueType </div> * </p> * * @param logicalOperators * @param cKey * @param relationalOperators * @param cValue * @param valueType * @return */ private SQLQueryUtil addCondition(LogicalOperators logicalOperators, String cKey, RelationalOperators relationalOperators, String cValue, ValueType valueType) { switch (valueType) { case STRING: conditionMap.put(logicalOperators.toString(), cKey.concat(" ").concat(relationalOperators.toString()).concat(" '").concat(cValue).concat("'")); break; case NUMBER: conditionMap.put(logicalOperators.toString(), cKey.concat(" ").concat(relationalOperators.toString()).concat(" ").concat(cValue)); break; default: conditionMap.put(logicalOperators.toString(), this.getDateTimeQuery(cKey, relationalOperators, cValue, valueType)); break; } return this; } /** * 目前仅支持 Oracle, MySQL ; 日期查询生成 其他数据库方式请根据需要自行扩展 */ private String getDateTimeQuery(String cKey, RelationalOperators ro, String cValue, ValueType vt) { if (USE_JDBC_DRIVER.toLowerCase().contains("oracle")) { switch (vt) { case DATE: return "to_char(".concat(cKey).concat(",'yyyy-mm-dd')").concat(ro.toString()).concat("'").concat(cValue).concat("'"); case TIME: return "to_char(".concat(cKey).concat(",'hh24:mi:ss')").concat(ro.toString()).concat("'").concat(cValue).concat("'"); case DATETIME: return "to_char(".concat(cKey).concat(",'yyyy-mm-dd hh24:mi:ss')").concat(ro.toString()).concat("'").concat(cValue).concat("'"); default: break; } } else if (USE_JDBC_DRIVER.toLowerCase().contains("mysql")) { switch (vt) { case DATE: return cKey.concat(ro.toString()).concat("UNIX_TIMESTAMP('").concat(cValue).concat(" 00:00:00')"); case TIME: throw new AppException(ResultCode.Failure, "暂不支持MySQL某段时间内查询,请确认日期后使用 ValueType.DATETIME 查询"); case DATETIME: return cKey.concat(ro.toString()).concat("UNIX_TIMESTAMP('").concat(cValue).concat("')"); default: break; } } return cKey.concat(" ").concat(ro.toString()).concat(" \"").concat(cValue).concat("\""); } private SQLQueryUtil addLikeCondition(LogicalOperators logicalOperators, String cKey, String cValue) { if (cValue.contains("%")) { conditionMap.put(logicalOperators.toString(), cKey.concat(" LIKE \"").concat(cValue).concat("\"")); } else { conditionMap.put(logicalOperators.toString(), cKey.concat(" LIKE \"%").concat(cValue).concat("%\"")); } return this; } private SQLQueryUtil addInCondition(LogicalOperators logicalOperators, String cKey, String cValue) { conditionMap.put(logicalOperators.toString(), cKey.concat(" IN ( ").concat(cValue).concat(" )")); return this; } private SQLQueryUtil addNotInCondition(LogicalOperators logicalOperators, String cKey, String cValue) { conditionMap.put(logicalOperators.toString(), cKey.concat(" NOT IN ( ").concat(cValue).concat(" )")); return this; } private SQLQueryUtil addOrderBy(String orderField, SortMethod sortMethod) { orderMap.put(orderField, sortMethod.toString()); return this; } /** * 添加分组字段 * * @param groupField * @return */ public SQLQueryUtil addGroupBy(String groupField) { groupList.add(groupField); return this; } /** * 添加 AND查询条件 * * @param cKey * @param relationalOperators * @param cValue * @param valueType * @return */ public SQLQueryUtil addAndCondition(String cKey, RelationalOperators relationalOperators, String cValue, ValueType valueType) { return this.addCondition(LogicalOperators.AND, cKey, relationalOperators, cValue, valueType); } /** * 添加 OR查询条件 * * @param cKey * @param relationalOperators * @param cValue * @param valueType * @return */ public SQLQueryUtil addOrCondition(String cKey, RelationalOperators relationalOperators, String cValue, ValueType valueType) { return this.addCondition(LogicalOperators.OR, cKey, relationalOperators, cValue, valueType); } /** * 添加 AND LIKE 查询条件 * * @param cKey * @param cValue * @return */ public SQLQueryUtil addAndLikeCondition(String cKey, String cValue) { return this.addLikeCondition(LogicalOperators.AND, cKey, cValue); } /** * 添加 OR LIKE 查询条件 * * @param cKey * @param cValue * @return */ public SQLQueryUtil addOrLikeCondition(String cKey, String cValue) { return this.addLikeCondition(LogicalOperators.OR, cKey, cValue); } /** * 添加 AND IN 查询条件 * * @param cKey * @param cValue * @return */ public SQLQueryUtil addAndInCondition(String cKey, String cValue) { return this.addInCondition(LogicalOperators.AND, cKey, cValue); } /** * 添加 OR IN 查询条件 * * @param cKey * @param cValue * @return */ public SQLQueryUtil addOrInCondition(String cKey, String cValue) { return this.addInCondition(LogicalOperators.OR, cKey, cValue); } /** * 添加 AND NOT IN 查询条件 * * @param cKey * @param cValue * @return */ public SQLQueryUtil addAndNotInCondition(String cKey, String cValue) { return this.addNotInCondition(LogicalOperators.AND, cKey, cValue); } /** * 添加 OR NOT IN 查询条件 * * @param cKey * @param cValue * @return */ public SQLQueryUtil addOrNotInCondition(String cKey, String cValue) { return this.addNotInCondition(LogicalOperators.OR, cKey, cValue); } /** * 添加正向排序字段 * * @param orderField * @return */ public SQLQueryUtil addAscOrderBy(String orderField) { return this.addOrderBy(orderField, SortMethod.ASC); } /* * 添加逆向排序字段 */ public SQLQueryUtil addDescOrderBy(String orderField) { return this.addOrderBy(orderField, SortMethod.DESC); } /** * 清除待查表和视图 * * @return */ public SQLQueryUtil clearTable() { tableMap.clear(); return this; } /** * 清除待查列 * * @return */ public SQLQueryUtil clearColumn() { columnMap.clear(); return this; } /** * 清除查询条件 * * @return */ public SQLQueryUtil clearCondition() { conditionMap.clear(); return this; } /** * 清除排序条件 * * @return */ public SQLQueryUtil clearOrder() { orderMap.clear(); return this; } /** * 清除分组列 * * @return */ public SQLQueryUtil clearGroup() { groupList.clear(); return this; } }
评论
2 楼
Vity
2013-06-21
xiaokang1582830 写道
有什么实质性的意义?
使用spring jdbc 的时候组装sql
1 楼
xiaokang1582830
2013-06-21
有什么实质性的意义?
相关推荐
写java程序时用来拼装sql语句时使用的小工具,在.net 4.0环境下运行。例如将 select a, b, c from abc where a like('3') 转换为: sql.append("select "); sql.append(" a, "); sql.append(" b, "); sql.append...
Java语言的动态SQL构建器。 例子 一些用法示例:选择 QueryBuilder query = new QueryBuilder () . select() .column( " s.name " ) .column( " count(s.impediments) AS total_impediments " ) .from() .table...
SpringBoot+JPA+Freemarker 生成动态SQL,通过Test下的 junit Test运行代码
8.1 动态SQL中的元素 开发人员在使用JDBC或其他类似的框架进行数据库开发时,通常都要根据需求去手动拼装SQL,这是一个非常麻烦且痛苦的工作,而MyBatis提供的对SQL语句动态组装的功能,恰能很好的解决这一麻烦工作...
2021版idea安装MyBatis Log Plugin不可用解决方案,idea安装插件2021idea-mybatis_log_plugin可以打印日志mysql
Java开发基于rmi的数据库中间件设计源码。分布式对象技术课程实践:基于rmi的数据库中间件...根据表名自动获取数据类型,从而在拼装SQL语句时决定数值是否加单引号; 提供事务确认和回滚处理。 接口设计如下表所示:
SQL语句高效解析处理 数据权限模块的核心之一就有SQL语句的高效解析处理,SQL处 理指根据当前登录人信息及数据权限策略生成一个带有数据权限处 理结果的SQL语句,所以这里对SQL语句的解析处理必须要求精确、 准确。...
这是一个简单的mybatis项目,包含mybatis需要用到的jar包,里面同时包含配置文件的书写,查询语句的配置调用以及存储过程的调用的书写方法,还有就是包含游标输出的存储过程,如何去接收返回游标的示例;还有就是一...
4.4 执行SQL语句 4.4.1 管理连接、语句和结果集 4.4.2 分析SQL异常 4.4.3 组装数据库 4.5 执行查询操作 4.5.1 预备语句 4.5.2 读取和写出LOB 4.5.3 SQL转义 4.5.4 多结果集 4.5.5 获取自动生成键 4.6 可滚动和可更新...
该组件初衷为:避免每个查询服务均进入java执行Controller,service,dao等各个分段,另外将sql语句预存下来,减少java开发工作量;替代原来每个接口都需要单独编写接口文档的过程。执行流程为:①添加SQL至sqltable...
2.注重安全性:过滤字符串中的单引号,因为SQL语句中的字符串是以单引号为分界符的,因此需要将单引号过滤掉,或者替换为两个单引号(在SQL语法中用两个单引号表示一个单引号),只要使用VBSCRIPT中的REPLACE函数就...
2.注重安全性:过滤字符串中的单引号,因为SQL语句中的字符串是以单引号为分界符的,因此需要将单引号过滤掉,或者替换为两个单引号(在SQL语法中用两个单引号表示一个单引号),只要使用VBSCRIPT中的REPLACE函数就...
比如数据库执行查询的sql语句存在字节集字段的,因为sql查询返回的是json数据,无法包含字节集数据,所以字节集字段无法使用(可考虑修改源码,对字节集进行base64成文本添加到返回json中或者以字节集文件形式等);...
计算机体系结构(组装,DOS 上的 tasm), 第二学期: 数据结构和算法(c), 面向对象编程(java), 第 3 学期: 应用面向对象编程(c# 和 .NET 框架,请查看 - 这是一项基于团队的作业), 数据库管理系统...
8.6.3 实现CBox类 406 8.6.4 定义CBox类 413 8.6.5 使用CBox类 423 8.7 组织程序代码 426 8.8 C++/CLI编程 428 8.8.1 在数值类中重载运算符 429 8.8.2 重载递增和递减运算符 434 8.8.3 在引用类中...
使用canal解析MySQL的binlog,投放进kafka,使用Flink消费kafka并把数据组装进Greenplum,后续将会添加更多的数据源和目标源。 工作流程 利用canal解析MySQL的binary log,并将解析的log投入kafka中。 使用mriya消费...
实现订制存储 3.1.4. 使用Zend_Auth 3.2. 数据库表认证 3.2.1. 简介 3.2.2. 高级使用:持久一个 DbTable 结果对象 3.2.3. 高级用法示例 3.3. 摘要式认证 3.3.1. 简介 3.3.2. 规范(Specifics) 3.3.3. ...