Spring NamedParameterJdbcTemplate命名参数查询条件封装, NamedParameterJdbcTemplate查询封装
Spring NamedParameterJdbcTemplate命名参数查询条件封装,
NamedParameterJdbcTemplate查询封装
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年7月25日
http://www.cnblogs.com/fanshuyao/
一、SqlBuffer查询对象封装(现在只能select语句的封装)
- import java.util.HashMap;
 - import java.util.Map;
 - public class SqlBuffer {
 - /**
 - * 空格
 - */
 - private final String SPACE = " ";
 - /**
 - * 冒号
 - */
 - private final String COLON = ":";
 - /**
 - * 逗号,
 - */
 - private final String COMMA = ",";
 - /**
 - * where关键字
 - */
 - private final String WHERE_SQL = "WHERE";
 - /**
 - * order by 关键字
 - */
 - private final String ORDER_BY_SQL = "ORDER BY";
 - /**
 - * limit关键字
 - */
 - private final String LIMIT_SQL = "LIMIT";
 - /**
 - * where 1=1条件
 - */
 - private final String WHERE_INIT = WHERE_SQL + " 1=1 ";
 - private final String LEFT_BRACKET = "(";
 - private final String RIGHT_BRACKET = ")";
 - /**
 - * 百分号%
 - */
 - private final String PERCENT_SIGN = "%";
 - /**
 - * 单引号 '
 - */
 - private final String SINGLE_QUOTE = "'";
 - private StringBuffer baseSql = new StringBuffer("");
 - private StringBuffer whereSql = new StringBuffer("");
 - private StringBuffer orderBySql = new StringBuffer("");
 - private StringBuffer limitSql = new StringBuffer("");
 - public Map<String, Object> paramsMap = new HashMap<String, Object>();
 - private int whereIndex = -1;
 - private int orderByIndex = -1;
 - private int limitIndex = -1;
 - private int offSize;
 - private int pageSize;
 - private boolean isNewStart = false;
 - private boolean isEndStart = false;
 - public SqlBuffer(){}
 - public SqlBuffer(String sql){
 - init(sql);
 - }
 - private int getWhereIndex(String sql){
 - if(sql != null){
 - return sql.indexOf(WHERE_SQL);
 - }
 - return -1;
 - }
 - private int getOrderByIndex(String sql){
 - if(sql != null){
 - return sql.indexOf(ORDER_BY_SQL);
 - }
 - return -1;
 - }
 - private int getLimitIndex(String sql){
 - if(sql != null){
 - return sql.indexOf(LIMIT_SQL);
 - }
 - return -1;
 - }
 - /**
 - * 判断有没有where查询语句,有则返回true
 - * @return
 - */
 - private boolean hadWhereSql(){
 - if(this.whereIndex > -1){
 - return true;
 - }
 - return false;
 - }
 - /**
 - * 判断有没有order by查询语句,有则返回true
 - * @return
 - */
 - private boolean hadOrderBySql(){
 - if(this.orderByIndex > -1){
 - return true;
 - }
 - return false;
 - }
 - /**
 - * 判断有没有limit查询语句,有则返回true
 - * @return
 - */
 - private boolean hadLimitSql(){
 - if(this.limitIndex > -1){
 - return true;
 - }
 - return false;
 - }
 - /**
 - * 初始化操作
 - * @param sql
 - */
 - private void init(String sql){
 - if(sql != null){
 - String sqlUpper = sql.trim().toUpperCase();
 - this.whereIndex = getWhereIndex(sqlUpper);
 - this.orderByIndex = getOrderByIndex(sqlUpper);
 - this.limitIndex = getLimitIndex(sqlUpper);
 - if(!hadWhereSql() && !hadOrderBySql() && !hadLimitSql()){
 - baseSql.append(sql);
 - }else{
 - if(hadWhereSql()){
 - baseSql.append(sql.substring(0, whereIndex));
 - }else if(!hadWhereSql() && hadOrderBySql()){
 - if(hadOrderBySql()){
 - baseSql.append(sql.substring(0, orderByIndex));
 - }
 - }else if(!hadWhereSql() && !hadOrderBySql() && hadLimitSql()){
 - baseSql.append(sql.substring(0, limitIndex));
 - }
 - }
 - int whereStartIndex = whereIndex + WHERE_SQL.length();//where条件不需要加where
 - if(hadWhereSql() && hadOrderBySql() && hadLimitSql()){
 - whereSql.append(sql.substring(whereStartIndex, orderByIndex));
 - orderBySql.append(sql.substring(orderByIndex, limitIndex));
 - limitSql.append(sql.substring(limitIndex));
 - }else if(hadWhereSql() && hadOrderBySql() && !hadLimitSql()){
 - whereSql.append(sql.substring(whereStartIndex, orderByIndex));
 - orderBySql.append(sql.substring(orderByIndex));
 - }else if(hadWhereSql() && !hadOrderBySql() && hadLimitSql()){
 - whereSql.append(sql.substring(whereStartIndex, limitIndex));
 - limitSql.append(sql.substring(limitIndex));
 - }else if(hadWhereSql() && !hadOrderBySql() && !hadLimitSql()){
 - whereSql.append(sql.substring(whereStartIndex));
 - }else if(!hadWhereSql() && hadOrderBySql() && hadLimitSql()){
 - orderBySql.append(sql.substring(orderByIndex, limitIndex));
 - limitSql.append(sql.substring(limitIndex));
 - }else if(!hadWhereSql() && hadOrderBySql() && !hadLimitSql()){
 - orderBySql.append(sql.substring(orderByIndex));
 - }else if(!hadWhereSql() && !hadOrderBySql() && hadLimitSql()){
 - limitSql.append(sql.substring(limitIndex));
 - }
 - }
 - }
 - /**
 - * and条件连接
 - * @param columnName 表的字段名称
 - * @param columnValue 查询字段名称对应的值
 - * <li>如果whereType为Null或者NotNull,该值可以为空</li>
 - * <li>如果whereType为IN,该值为List类型,如:Arrays.asList("aa", "bb")</li>
 - * @param whereType WhereType枚举,如like,>=
 - * @return SqlBuffer
 - */
 - public SqlBuffer and(String columnName, Object columnValue, WhereType whereType){
 - return add(ConnectType.AND, columnName, columnValue, null, whereType);
 - }
 - /**
 - * or条件连接,使用columnName作为命名参数
 - * @param columnName 表的字段名称
 - * @param columnValue 查询字段名称对应的值
 - * <li>如果whereType为Null或者NotNull,该值可以为空</li>
 - * <li>如果whereType为IN,该值为List类型,如:Arrays.asList("aa", "bb")</li>
 - * @param whereType WhereType枚举,如like,>=
 - * @return SqlBuffer
 - */
 - public SqlBuffer or(String columnName, Object columnValue, WhereType whereType){
 - return add(ConnectType.OR, columnName, columnValue, null, whereType);
 - }
 - /**
 - * 加上表字段不为空的判断
 - * <li>如columnName is not null</li>
 - * @param connectType ConnectType枚举
 - * @param columnName 表的字段名称
 - * @return SqlBuffer
 - */
 - public SqlBuffer isNotNull(ConnectType connectType, String columnName){
 - return add(connectType, columnName, null, null, WhereType.NOT_NULL);
 - }
 - /**
 - * 加上表字段不为空的判断,使用And连接
 - * <li>如columnName is not null</li>
 - * @param columnName 表的字段名称
 - * @return SqlBuffer
 - */
 - public SqlBuffer isNotNull(String columnName){
 - return add(ConnectType.AND, columnName, null, null, WhereType.NOT_NULL);
 - }
 - /**
 - * 加上表字段为空的判断
 - * <li>如columnName is null</li>
 - * @param connectType ConnectType枚举
 - * @param columnName 表的字段名称
 - * @return SqlBuffer
 - */
 - public SqlBuffer isNull(ConnectType connectType, String columnName){
 - return add(connectType, columnName, null, null, WhereType.NULL);
 - }
 - /**
 - * 加上表字段为空的判断,使用And连接
 - * <li>如columnName is not null</li>
 - * @param columnName 表的字段名称
 - * @return SqlBuffer
 - */
 - public SqlBuffer isNull(String columnName){
 - return add(ConnectType.AND, columnName, null, null, WhereType.NULL);
 - }
 - /**
 - * and条件连接,使用columnName作为命名参数
 - * @param columnName 表的字段名称
 - * @param columnValue 查询字段名称对应的值
 - * <li>如果whereType为Null或者NotNull,该值可以为空</li>
 - * <li>如果whereType为IN,该值为List类型</li>
 - * <li>如果whereType为IN,该值为List类型,如:Arrays.asList("aa", "bb")</li>
 - * @param placeholder 命名参数
 - * <li>如果为Null,则使用表的字段名称作为命名参数</li>
 - * @param whereType WhereType枚举,如like,>=
 - * @return SqlBuffer
 - */
 - public SqlBuffer and(String columnName, Object columnValue, String placeholder, WhereType whereType){
 - if(StrUtils.isBlank(columnName)){
 - return this;
 - }
 - return add(ConnectType.AND, columnName, columnValue, placeholder, whereType);
 - }
 - /**
 - * or条件连接
 - * @param columnName 表的字段名称
 - * @param columnValue 查询字段名称对应的值
 - * <li>如果whereType为Null或者NotNull,该值可以为空</li>
 - * <li>如果whereType为IN,该值为List类型,如:Arrays.asList("aa", "bb")</li>
 - * @param placeholder 命名参数
 - * <li>如果为Null,则使用表的字段名称作为命名参数</li>
 - * @param whereType WhereType枚举,如like,>=
 - * @return SqlBuffer
 - */
 - public SqlBuffer or(String columnName, Object columnValue, String placeholder, WhereType whereType){
 - if(StrUtils.isBlank(columnName)){
 - return this;
 - }
 - return add(ConnectType.OR, columnName, columnValue, placeholder, whereType);
 - }
 - /**
 - * 命名参数查询,使用columnName作为命名参数
 - * @param connectType ConnectType枚举
 - * @param columnName 表的字段名称
 - * @param columnValue 查询字段名称对应的值
 - * <li>如果whereType为Null或者NotNull,该值可以为空</li>
 - * <li>如果whereType为IN,该值为List类型,如:Arrays.asList("aa", "bb")</li>
 - * @param whereType WhereType枚举,如like,>=
 - * @return SqlBuffer
 - */
 - public SqlBuffer add(ConnectType connectType, String columnName, Object columnValue, WhereType whereType){
 - return add(connectType, columnName, columnValue, null, whereType);
 - }
 - /**
 - * 命名参数查询
 - * @param connectType ConnectType枚举
 - * @param columnName 表的字段名称
 - * @param columnValue 查询字段名称对应的值
 - * <li>如果whereType为Null或者NotNull,该值可以为空</li>
 - * <li>如果whereType为IN,该值为List类型,如:Arrays.asList("aa", "bb")</li>
 - * @param placeholder 命名参数
 - * <li>如果为Null,则使用表的字段名称作为命名参数</li>
 - * @param whereType WhereType枚举,如like,>=
 - * @return SqlBuffer
 - */
 - public SqlBuffer add(ConnectType connectType, String columnName, Object columnValue, String placeholder, WhereType whereType){
 - if(StrUtils.isBlank(columnName)){
 - return this;
 - }
 - this.whereSql.append(SPACE).append(connectType.getValue());
 - if(this.isNewStart){
 - this.whereSql.append(SPACE).append(LEFT_BRACKET);
 - this.isNewStart = false;
 - }
 - this.whereSql.append(SPACE).append(columnName);
 - //组装参数
 - if(StrUtils.isBlank(placeholder)){//命名参数为空,则使用字段名
 - placeholder = columnName;
 - }
 - if(WhereType.LIKE == whereType){
 - //LIKE '%' :username '%' ,:username 两边一定要有空格,如果没有空格,是查询不到数据的
 - this.whereSql.append(SPACE).append(whereType.getValue())
 - .append(SPACE).append(SINGLE_QUOTE).append(PERCENT_SIGN).append(SINGLE_QUOTE).append(SPACE)
 - .append(COLON).append(placeholder)
 - .append(SPACE).append(SINGLE_QUOTE).append(PERCENT_SIGN).append(SINGLE_QUOTE).append(SPACE);
 - this.getParamsMap().put(placeholder, columnValue);
 - // 这种方法是在值里放%,如 "%" + username + "%"
 - /*this.whereSql.append(SPACE).append(whereType.getValue())
 - .append(SPACE)
 - .append(COLON).append(placeholder);*/
 - }else if(WhereType.LIKE_LEFT == whereType){
 - this.whereSql.append(SPACE).append(whereType.getValue())
 - .append(SPACE).append(SINGLE_QUOTE).append(PERCENT_SIGN).append(SINGLE_QUOTE).append(SPACE)
 - .append(COLON).append(placeholder).append(SPACE);
 - this.getParamsMap().put(placeholder, columnValue);
 - }else if(WhereType.LIKE_RIGHT == whereType){
 - this.whereSql.append(SPACE).append(whereType.getValue())
 - .append(SPACE).append(COLON).append(placeholder)
 - .append(SPACE).append(SINGLE_QUOTE).append(PERCENT_SIGN).append(SINGLE_QUOTE).append(SPACE);
 - this.getParamsMap().put(placeholder, columnValue);
 - }else if(WhereType.NULL == whereType || WhereType.NOT_NULL == whereType){
 - this.whereSql.append(SPACE).append(whereType.getValue());
 - // 因为is null或is not null不需要参数值,所以参数Map不增加值
 - }else if(WhereType.IN == whereType){
 - // in (:userids)
 - this.whereSql.append(SPACE).append(whereType.getValue())
 - .append(SPACE).append(LEFT_BRACKET)
 - .append(COLON).append(placeholder)
 - .append(RIGHT_BRACKET);
 - this.getParamsMap().put(placeholder, columnValue);
 - }else{
 - this.whereSql.append(SPACE).append(whereType.getValue())
 - .append(SPACE).append(COLON).append(placeholder);
 - this.getParamsMap().put(placeholder, columnValue);
 - }
 - return this;
 - }
 - /**
 - * 把之前的查询条件用括号包括
 - * @return
 - */
 - public SqlBuffer endBefore(){
 - if(hadWhereSql()){
 - this.whereSql.insert(0, SPACE + LEFT_BRACKET).append(RIGHT_BRACKET);
 - }else{
 - String beginFlag = this.whereSql.substring(0, 4);
 - if(beginFlag.toUpperCase().indexOf(ConnectType.AND.getValue()) > -1){
 - this.whereSql.insert(4, SPACE + LEFT_BRACKET).append(RIGHT_BRACKET);
 - }else{
 - this.whereSql.insert(3, SPACE + LEFT_BRACKET).append(RIGHT_BRACKET);
 - }
 - }
 - return this;
 - }
 - /**
 - * 为后面的查询条件加上左括号,结束后使用newEnd()加上右括号
 - * @return
 - */
 - public SqlBuffer newStart(){
 - this.isNewStart = true;
 - this.isEndStart = true;
 - return this;
 - }
 - /**
 - * 为后面的查询条件加上右括号,先使用newStart()
 - * @return
 - */
 - public SqlBuffer newEnd(){
 - if(this.isEndStart){
 - this.whereSql.append(SPACE).append(RIGHT_BRACKET);
 - }
 - this.isEndStart = false;
 - return this;
 - }
 - /**
 - * 排序
 - * @param columnName 表的列名称
 - * @param orderByType OrderByType枚举
 - * @return
 - */
 - public SqlBuffer orderBy(String columnName, OrderByType orderByType){
 - if(hadOrderBySql()){
 - this.orderBySql.append(SPACE).append(COMMA).append(columnName).append(SPACE).append(orderByType.getValue());
 - }else{
 - this.orderBySql.append(ORDER_BY_SQL).append(SPACE).append(columnName).append(SPACE).append(orderByType.getValue());
 - this.orderByIndex = 1;
 - }
 - return this;
 - }
 - /**
 - * 升序排序
 - * @param columnName 表的列名称
 - * @return
 - */
 - public SqlBuffer orderBy(String columnName){
 - return orderBy(columnName, OrderByType.ASC);
 - }
 - /**
 - * 分页查询条件
 - * @param offSize
 - * @param pageSize
 - * @return
 - */
 - public SqlBuffer limit(int offSize, int pageSize){
 - if(offSize < 0){
 - offSize = 0;
 - }
 - if(pageSize < 0){
 - pageSize = 10;
 - }
 - this.offSize = offSize;
 - this.pageSize = pageSize;
 - if(hadLimitSql()){
 - this.limitSql.delete(0, limitSql.length())
 - .append(LIMIT_SQL).append(SPACE)
 - .append(offSize).append(COMMA).append(pageSize);
 - }else{
 - this.limitSql.append(LIMIT_SQL).append(SPACE)
 - .append(offSize).append(COMMA).append(pageSize);
 - this.limitIndex = 1;
 - }
 - return this;
 - }
 - /**
 - * 分页查询条件
 - * @param pageSize
 - * @return
 - */
 - public SqlBuffer limit(int pageSize){
 - return limit(0, pageSize);
 - }
 - /**
 - * 获取SqlBuffer拼接的sql语句
 - * @return
 - */
 - public String getSql(){
 - StringBuffer result = new StringBuffer("");
 - result.append(baseSql).append(SPACE);
 - if(!hadWhereSql()){
 - if(this.whereSql.length() > 0){
 - result.append(WHERE_INIT + SPACE);
 - }
 - }else{
 - result.append(WHERE_SQL + SPACE);
 - }
 - result.append(whereSql).append(SPACE)
 - .append(orderBySql).append(SPACE)
 - .append(limitSql).append(SPACE);
 - return result.toString();
 - }
 - /**
 - * 获取SqlBuffer拼接的countSql语句
 - * @return
 - */
 - public String getCountSql(){
 - StringBuffer result = new StringBuffer("");
 - result.append(baseSql).append(SPACE);
 - if(!hadWhereSql()){
 - if(this.whereSql.length() > 0){
 - result.append(WHERE_INIT + SPACE);
 - }
 - }else{
 - result.append(WHERE_SQL + SPACE);
 - }
 - result.append(whereSql).append(SPACE);
 - return "select count(*) from ("+result.toString()+") _temp_count";
 - //return result.toString();
 - }
 - /**
 - * 获取SqlBuffer拼接的sql语句
 - * @return
 - */
 - public String toString(){
 - return this.getSql();
 - }
 - @SuppressWarnings("unused")
 - private StringBuffer getBaseSql() {
 - return baseSql;
 - }
 - @SuppressWarnings("unused")
 - private void setBaseSql(StringBuffer baseSql) {
 - this.baseSql = baseSql;
 - }
 - @SuppressWarnings("unused")
 - private StringBuffer getWhereSql() {
 - return whereSql;
 - }
 - @SuppressWarnings("unused")
 - private void setWhereSql(StringBuffer whereSql) {
 - this.whereSql = whereSql;
 - }
 - @SuppressWarnings("unused")
 - private StringBuffer getOrderBySql() {
 - return orderBySql;
 - }
 - @SuppressWarnings("unused")
 - private void setOrderBySql(StringBuffer orderBySql) {
 - this.orderBySql = orderBySql;
 - }
 - @SuppressWarnings("unused")
 - private StringBuffer getLimitSql() {
 - return limitSql;
 - }
 - @SuppressWarnings("unused")
 - private void setLimitSql(StringBuffer limitSql) {
 - this.limitSql = limitSql;
 - }
 - @SuppressWarnings("unused")
 - private int getWhereIndex() {
 - return whereIndex;
 - }
 - @SuppressWarnings("unused")
 - private void setWhereIndex(int whereIndex) {
 - this.whereIndex = whereIndex;
 - }
 - public int getOrderByIndex() {
 - return orderByIndex;
 - }
 - public void setOrderByIndex(int orderByIndex) {
 - this.orderByIndex = orderByIndex;
 - }
 - @SuppressWarnings("unused")
 - private int getLimitIndex() {
 - return limitIndex;
 - }
 - @SuppressWarnings("unused")
 - private void setLimitIndex(int limitIndex) {
 - this.limitIndex = limitIndex;
 - }
 - public Map<String, Object> getParamsMap() {
 - return paramsMap;
 - }
 - public void setParamsMap(Map<String, Object> paramsMap) {
 - this.paramsMap = paramsMap;
 - }
 - public int getOffSize() {
 - return offSize;
 - }
 - public void setOffSize(int offSize) {
 - this.offSize = offSize;
 - }
 - public int getPageSize() {
 - return pageSize;
 - }
 - public void setPageSize(int pageSize) {
 - this.pageSize = pageSize;
 - }
 - }
 
二、定义的枚举
1、ConnectType
- public enum ConnectType {
 - AND{
 - @Override
 - public String getValue() {
 - return "AND";
 - }
 - },
 - OR{
 - @Override
 - public String getValue() {
 - return "OR";
 - }
 - };
 - public abstract String getValue();
 - }
 
2、OrderByType
- public enum OrderByType {
 - DESC{
 - @Override
 - public String getValue() {
 - return "DESC";
 - }
 - },
 - ASC{
 - @Override
 - public String getValue() {
 - return "ASC";
 - }
 - };
 - public abstract String getValue();
 - }
 
3、WhereType
- public enum WhereType {
 - EQUALS{
 - @Override
 - public String getValue() {
 - return "=";
 - }
 - },
 - NOT_EQUALS{
 - @Override
 - public String getValue() {
 - return "!=";
 - }
 - },
 - LIKE{
 - @Override
 - public String getValue() {
 - return "LIKE";
 - }
 - },
 - LIKE_LEFT{
 - @Override
 - public String getValue() {
 - return "LIKE";
 - }
 - },
 - LIKE_RIGHT{
 - @Override
 - public String getValue() {
 - return "LIKE";
 - }
 - },
 - GREATER_THAN{
 - @Override
 - public String getValue() {
 - return ">";
 - }
 - },
 - GREATER_THAN_EQUALS{
 - @Override
 - public String getValue() {
 - return ">=";
 - }
 - },
 - LESS_THAN{
 - @Override
 - public String getValue() {
 - return "<";
 - }
 - },
 - LESS_THAN_EQUALS{
 - @Override
 - public String getValue() {
 - return "<=";
 - }
 - },
 - NULL{
 - @Override
 - public String getValue() {
 - return "is null";
 - }
 - },
 - NOT_NULL{
 - @Override
 - public String getValue() {
 - return "is not null";
 - }
 - },
 - IN{
 - @Override
 - public String getValue() {
 - return "in";
 - }
 - };
 - public abstract String getValue();
 - }
 
三、用到的工具类:StrUtils
- import java.util.ArrayList;
 - import java.util.Calendar;
 - import java.util.List;
 - import java.util.Map;
 - import java.util.UUID;
 - //import cn.imovie.common.utils.RegUtils;
 - public class StrUtils {
 - /**
 - * 随机获取数字和大写英文字母组合的字符串
 - *
 - * @param size
 - * 返回的字符串的位数,如果小于1,则默认是6
 - * @return String
 - * @since 2015-09-25
 - */
 - public static String getRandomLetterAndDigital(int size) {
 - String str = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";// 去掉容易混淆字符:0与O,1与I
 - StringBuffer sb = new StringBuffer();
 - if (size < 1) {
 - size = 6;
 - }
 - for (int i = 0; i < size; i++) {
 - int ran = (int) (Math.random() * str.length());
 - sb.append(str.charAt(ran));
 - }
 - return sb.toString().trim();
 - }
 - /**
 - * 随机获取大/小写英文字母组合的字符串
 - *
 - * @param size
 - * 返回的字符串的位数,如果小于1,则默认是6
 - * @return String
 - * @since 2015-09-25
 - */
 - public static String getLetter(int size) {
 - String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 - StringBuffer sb = new StringBuffer();
 - if (size < 1) {
 - size = 6;
 - }
 - for (int i = 0; i < size; i++) {
 - int ran = (int) (Math.random() * str.length());
 - sb.append(str.charAt(ran));
 - }
 - return sb.toString().trim();
 - }
 - /**
 - * 随机获取大写英文字母组合的字符串
 - *
 - * @param size
 - * 返回的字符串的位数,如果小于1,则默认是6
 - * @return String
 - * @since 2015-09-25
 - */
 - public static String getUpperLetter(int size) {
 - String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 - StringBuffer sb = new StringBuffer();
 - if (size < 1) {
 - size = 6;
 - }
 - for (int i = 0; i < size; i++) {
 - int ran = (int) (Math.random() * str.length());
 - sb.append(str.charAt(ran));
 - }
 - return sb.toString().trim();
 - }
 - /**
 - * 随机获取数字字符串
 - *
 - * @param size
 - * 返回的字符串的位数
 - * @return String
 - * @since 2015-09-25
 - */
 - public static String getRandomDigital(int size) {
 - String str = "1234567890";
 - StringBuffer sb = new StringBuffer();
 - if (size < 1) {
 - return null;
 - } else {
 - for (int i = 0; i < size; i++) {
 - int ran = (int) (Math.random() * 10);
 - sb.append(str.charAt(ran));
 - }
 - return sb.toString().trim();
 - }
 - }
 - /**
 - * 获取随机数字,同getRandomDigital
 - *
 - * @param size
 - * @return
 - */
 - public static String getNumber(int size) {
 - return getRandomDigital(size);
 - }
 - /**
 - * 生成年月日时分秒毫秒(20120905050602000)
 - *
 - * @return
 - * @since 2015-09-25
 - */
 - public static String getYYYYMMDDHHmmssmilliSecond() {
 - StringBuffer str = new StringBuffer("");
 - String strMonth = "";
 - String strDate = "";
 - String strHour = "";
 - String strMinute = "";
 - String strSecond = "";
 - String strMilliSecond = "";
 - Calendar cal = Calendar.getInstance();
 - int year = cal.get(Calendar.YEAR);
 - int month = cal.get(Calendar.MONTH) + 1;
 - int date = cal.get(Calendar.DATE);
 - int hour = cal.get(Calendar.HOUR_OF_DAY);
 - int minute = cal.get(Calendar.MINUTE);
 - int second = cal.get(Calendar.SECOND);
 - int milliSecond = cal.get(Calendar.MILLISECOND);
 - if (month < 10) {
 - strMonth = "0" + month;
 - } else {
 - strMonth = String.valueOf(month);
 - }
 - if (date < 10) {
 - strDate = "0" + date;
 - } else {
 - strDate = String.valueOf(date);
 - }
 - if (hour < 10) {
 - strHour = "0" + hour;
 - } else {
 - strHour = String.valueOf(hour);
 - }
 - if (minute < 10) {
 - strMinute = "0" + minute;
 - } else {
 - strMinute = String.valueOf(minute);
 - }
 - if (second < 10) {
 - strSecond = "0" + second;
 - } else {
 - strSecond = String.valueOf(second);
 - }
 - if (milliSecond < 10) {
 - strMilliSecond = "00" + milliSecond;
 - } else if (milliSecond < 100) {
 - strMilliSecond = "0" + milliSecond;
 - } else {
 - strMilliSecond = String.valueOf(milliSecond);
 - }
 - return str.append(String.valueOf(year).toString().trim()).append(strMonth.trim()).append(strDate.trim())
 - .append(strHour.trim()).append(strMinute.trim()).append(strSecond.trim()).append(strMilliSecond.trim())
 - .toString();
 - }
 - /**
 - * 生成年月日(20120905050602000)
 - *
 - * @return
 - * @since 2015-09-25
 - */
 - public static String getYYYYMMDD() {
 - StringBuffer str = new StringBuffer("");
 - String strMonth = "";
 - String strDate = "";
 - Calendar cal = Calendar.getInstance();
 - int year = cal.get(Calendar.YEAR);
 - int month = cal.get(Calendar.MONTH) + 1;
 - int date = cal.get(Calendar.DATE);
 - if (month < 10) {
 - strMonth = "0" + month;
 - } else {
 - strMonth = String.valueOf(month);
 - }
 - if (date < 10) {
 - strDate = "0" + date;
 - } else {
 - strDate = String.valueOf(date);
 - }
 - return str.append(String.valueOf(year).toString().trim()).append(strMonth.trim()).append(strDate.trim())
 - .toString();
 - }
 - /**
 - * 获取uuid,有横杠(36位)
 - *
 - * @return
 - * @since 2015-10-14
 - */
 - public static String getUUID() {
 - return UUID.randomUUID().toString();
 - }
 - /**
 - * 获取uuid,无横杠(32位)
 - *
 - * @return
 - * @author lqyao
 - * @since 2015-10-14
 - */
 - public static String getUUIDNumberOnly() {
 - return UUID.randomUUID().toString().replaceAll("-", "");
 - }
 - /**
 - * 移除字符串最后一个字符
 - *
 - * @return
 - * @since 2015-10-14
 - */
 - public static String removeLastCode(String str) {
 - if (str == null || str.length() < 1) {
 - return str;
 - }
 - return str.substring(0, str.length() - 1);
 - }
 - /**
 - * 第一个字符变大写
 - *
 - * @param str
 - * @return
 - */
 - public static String firstCodeToUpperCase(String str) {
 - if (isBlank(str)) {
 - return str;
 - }
 - String strTrim = str.trim();
 - return String.valueOf(strTrim.charAt(0)).toUpperCase() + strTrim.substring(1, strTrim.length());
 - }
 - /**
 - * 获取字符串最后一个字符
 - *
 - * @return
 - * @since 2016-01-13
 - */
 - public static String getLastCode(String str) {
 - if (str == null || str.length() < 1) {
 - return "";
 - }
 - return str.substring(str.length() - 1);
 - }
 - /**
 - * 获取第一个id
 - *
 - * @param str
 - * 字符串
 - * @return id
 - */
 - public static String getFirstId(String str, String spiltCode) {
 - if (spiltCode == null) {
 - spiltCode = ",";
 - }
 - if (!StrUtils.isEmpty(str)) {
 - if (str.indexOf(spiltCode) > -1) {
 - return str.substring(0, str.indexOf(spiltCode)).trim();
 - }
 - }
 - return str;
 - }
 - /**
 - * 去相同部分
 - *
 - * @param originalStr
 - * 原字符串
 - * @param deleteStr
 - * 需要去掉的字符串
 - * @return string
 - * @author lqy
 - */
 - public static String removeSamePart(String originalStr, String deleteStr) {
 - if (originalStr != null && deleteStr != null) {
 - originalStr = originalStr.replaceAll("\\(", "(");
 - originalStr = originalStr.replaceAll("\\)", ")");
 - originalStr = originalStr.replaceAll(" | ", "");
 - deleteStr = deleteStr.replaceAll("\\(", "(");
 - deleteStr = deleteStr.replaceAll("\\)", ")");
 - deleteStr = deleteStr.replaceAll(" | ", "");
 - if (originalStr.indexOf(deleteStr) > -1) {
 - originalStr = originalStr.replaceAll(deleteStr, "");
 - }
 - }
 - return originalStr;
 - }
 - /**
 - * 拆分字符串获取数组
 - *
 - * @param str
 - * 字符串
 - * @param spiltCode
 - * 拆分符号
 - * @return String[]
 - */
 - public static String[] getArrayAfterSpilt(String str, String spiltCode) {
 - if (str == null || str.trim().equals("")) {
 - return null;
 - } else {
 - if (spiltCode == null || spiltCode.trim().equals("")) {
 - spiltCode = ",";
 - }
 - return str.split(spiltCode);
 - }
 - }
 - /**
 - * 拆分字符串获取Ids
 - *
 - * @param idsString
 - * id字符串
 - * @param spiltCode
 - * 拆分符号
 - * @return ids
 - */
 - public static int[] getIdsAfterSpilt(String idsString, String spiltCode) {
 - List<Integer> idList = new ArrayList<Integer>();
 - if (idsString == null || idsString.trim().equals("")) {
 - return null;
 - } else {
 - if (spiltCode == null || spiltCode.trim().equals("")) {
 - spiltCode = ",";
 - }
 - String[] idArray = idsString.split(spiltCode);
 - if (idArray != null && idArray.length > 0) {
 - for (String string : idArray) {
 - if (string != null && !string.trim().equals("")) {
 - idList.add(Integer.parseInt(string.trim()));
 - }
 - }
 - }
 - }
 - if (idList != null && idList.size() > 0) {
 - int[] ids = new int[idList.size()];
 - for (int j = 0; j < idList.size(); j++) {
 - ids[j] = idList.get(j);
 - }
 - return ids;
 - }
 - return null;
 - }
 - /**
 - *
 - * @param obj
 - * @return obj == null;
 - */
 - public static boolean isNull(Object obj) {
 - return obj == null;
 - }
 - /**
 - * 判断list是否为Null
 - *
 - * @param list
 - * @return
 - */
 - public static <T> boolean isNullList(List<T> list) {
 - return (list == null);
 - }
 - /**
 - * 判断list是否为空
 - *
 - * @param list
 - * @return (list == null) || (list.size() < 1)
 - */
 - public static <T> boolean isEmptyList(List<T> list) {
 - return (list == null) || (list.size() < 1);
 - }
 - /**
 - * 判断Map是否为Null
 - *
 - * @param map
 - * @return
 - */
 - public static <K, V> boolean isNullMap(Map<K, V> map) {
 - return (map == null);
 - }
 - /**
 - * 判断Map是否为空
 - *
 - * @param map
 - * @return
 - */
 - public static <K, V> boolean isEmptyMap(Map<K, V> map) {
 - return (map == null || map.size() < 1);
 - }
 - /**
 - * 判断数组是否为Null
 - *
 - * @param obj
 - * @return
 - */
 - public static boolean isNullArray(Object[] obj) {
 - return (obj == null);
 - }
 - /**
 - * 判断数组是否为空
 - *
 - * @param obj
 - * @return
 - */
 - public static boolean isEmptyArray(Object[] obj) {
 - return (obj == null || obj.length < 1);
 - }
 - /**
 - * <p>
 - * Checks if a String is empty ("") or null.
 - * </p>
 - *
 - * <pre>
 - * StringUtils.isEmpty(null) = true
 - * StringUtils.isEmpty("") = true
 - * StringUtils.isEmpty(" ") = false
 - * StringUtils.isEmpty("bob") = false
 - * StringUtils.isEmpty(" bob ") = false
 - * </pre>
 - *
 - * <p>
 - * NOTE: This method changed in Lang version 2.0. It no longer trims the
 - * String. That functionality is available in isBlank().
 - * </p>
 - *
 - * @param str
 - * the String to check, may be null
 - * @return <code>true</code> if the String is empty or null
 - */
 - public static boolean isEmpty(String str) {
 - return str == null || str.length() == 0;
 - }
 - /**
 - * <p>
 - * Checks if a String is whitespace, empty ("") or null.
 - * </p>
 - *
 - * <pre>
 - * StringUtils.isBlank(null) = true
 - * StringUtils.isBlank("") = true
 - * StringUtils.isBlank(" ") = true
 - * StringUtils.isBlank("bob") = false
 - * StringUtils.isBlank(" bob ") = false
 - * </pre>
 - *
 - * @param str
 - * the String to check, may be null
 - * @return <code>true</code> if the String is null, empty or whitespace
 - * @since 2.0
 - */
 - public static boolean isBlank(String str) {
 - int strLen;
 - if (str == null || (strLen = str.length()) == 0) {
 - return true;
 - }
 - for (int i = 0; i < strLen; i++) {
 - if ((Character.isWhitespace(str.charAt(i)) == false)) {
 - return false;
 - }
 - }
 - return true;
 - }
 - /**
 - * <p>
 - * Checks if the String contains only whitespace.
 - * </p>
 - *
 - * <p>
 - * <code>null</code> will return <code>false</code>. An empty String ("")
 - * will return <code>true</code>.
 - * </p>
 - *
 - * <pre>
 - * StringUtils.isWhitespace(null) = false
 - * StringUtils.isWhitespace("") = true
 - * StringUtils.isWhitespace(" ") = true
 - * StringUtils.isWhitespace("abc") = false
 - * StringUtils.isWhitespace("ab2c") = false
 - * StringUtils.isWhitespace("ab-c") = false
 - * </pre>
 - *
 - * @param str
 - * the String to check, may be null
 - * @return <code>true</code> if only contains whitespace, and is non-null
 - * @since 2.0
 - */
 - public static boolean isWhitespace(String str) {
 - if (str == null) {
 - return false;
 - }
 - int sz = str.length();
 - for (int i = 0; i < sz; i++) {
 - if ((Character.isWhitespace(str.charAt(i)) == false)) {
 - return false;
 - }
 - }
 - return true;
 - }
 - /**
 - * 变成中文括号
 - *
 - * @param str
 - * @return
 - */
 - public static String bracketToChinese(String str) {
 - if (isBlank(str)) {
 - return str;
 - }
 - String strTrim = str.trim();
 - strTrim = strTrim.replaceAll("\\(", "(").replaceAll("\\)", ")");
 - return strTrim;
 - }
 - /**
 - * 变成英文括号
 - *
 - * @param str
 - * @return
 - */
 - public static String bracketToEnglish(String str) {
 - if (isBlank(str)) {
 - return str;
 - }
 - String strTrim = str.trim();
 - strTrim = strTrim.replaceAll("(", "(").replaceAll(")", ")");
 - return strTrim;
 - }
 - /**
 - * 替换字符串
 - *
 - * @param str
 - * @param sourceStr,如果是特殊字符,如英文()、[]等,要使用\\(
 - * @param targetStr
 - * @return
 - */
 - public static String replaceStr(String str, String sourceStr, String targetStr) {
 - if (isBlank(str)) {
 - return str;
 - }
 - String strTrim = str.trim();
 - strTrim = strTrim.replaceAll(sourceStr, targetStr);
 - return strTrim;
 - }
 - }
 
四、Dao使用例子:
- @Override
 - public <E> List<E> queryForList(String sql, Map<String, Object> paramsMap, Class<E> clazz) {
 - return namedParameterJdbcTemplate.query(sql,paramsMap,new BeanPropertyRowMapper(clazz));
 - }
 - @Override
 - public List<Map<String, Object>> queryForList(SqlBuffer sqlBuffer) {
 - return namedParameterJdbcTemplate.queryForList(sqlBuffer.getSql(), sqlBuffer.getParamsMap());
 - }
 - @SuppressWarnings("rawtypes")
 - @Override
 - public List<?> queryForList(SqlBuffer sqlBuffer, Class<?> clazz) {
 - return namedParameterJdbcTemplate.query(sqlBuffer.getSql(), sqlBuffer.getParamsMap(),
 - new BeanPropertyRowMapper(clazz));
 - }
 - @Override
 - public int queryForInt(SqlBuffer sqlBuffer) {
 - return namedParameterJdbcTemplate.queryForObject(sqlBuffer.getCountSql(), sqlBuffer.getParamsMap(), int.class);
 - }
 - @Override
 - public String queryForString(SqlBuffer sqlBuffer) {
 - return namedParameterJdbcTemplate.queryForObject(sqlBuffer.getCountSql(), sqlBuffer.getParamsMap(),
 - String.class);
 - }
 - @Override
 - public int getCount(SqlBuffer sqlBuffer){
 - return namedParameterJdbcTemplate.queryForObject(sqlBuffer.getCountSql(), sqlBuffer.getParamsMap(), int.class);
 - }
 
五、SqlBuffer 使用例子:
- SqlBuffer sqlBuffer6 = new SqlBuffer("SELECT ja.*,jaa.`attr_name`,jaa.`attr_value` FROM jc_advertising ja LEFT JOIN jc_advertising_attr jaa ON ja.`advertising_id`=jaa.`advertising_id`");
 - sqlBuffer6.and("jaa.attr_name", Arrays.asList("image_title","image_url"), WhereType.IN);
 - sqlBuffer6.and("ja.site_id", null, WhereType.NOT_NULL).isNull("ja.ad_code");
 - sqlBuffer6.and("ja.ad_name", "banner", WhereType.EQUALS);
 - List<Aaa> list = (List<Aaa>) testSevice.queryForList(sqlBuffer6, Aaa.class);
 - for (Aaa aaa : list) {
 - System.out.println("aaa.getAdvertisingId()="+aaa.getAdvertisingId());
 - System.out.println("aaa.getAdName()="+aaa.getAdName());
 
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
©Copyright 蕃薯耀 2017年7月25日
http://www.cnblogs.com/fanshuyao/
Spring NamedParameterJdbcTemplate命名参数查询条件封装, NamedParameterJdbcTemplate查询封装的更多相关文章
- Atitit.列表页面and条件查询的实现最佳实践(1)------设置查询条件and提交查询and返回json数据
		
Atitit.列表页面and条件查询的实现最佳实践(1)------设置查询条件and提交查询and返回json数据 1. 1. 配置条件字段@Conditional 1 1 2. 2. 配置条件字段 ...
 - 序列化表单为json对象,datagrid带额外参提交一次查询 后台用Spring data JPA 实现带条件的分页查询 多表关联查询
		
查询窗口中可以设置很多查询条件 表单中输入的内容转为datagrid的load方法所需的查询条件向原请求地址再次提出新的查询,将结果显示在datagrid中 转换方法看代码注释 <td cols ...
 - Spring Data JPA 复杂/多条件组合分页查询
		
推荐视频: http://www.icoolxue.com/album/show/358 public Map<String, Object> getWeeklyBySearch(fina ...
 - spring mongodb分页,动态条件、字段查询
		
使用MongRepository public interface VideoRepository extends MongoRepository<Video, String> { Vid ...
 - 【mysql】 mybatis实现 主从表 left join  1:n 一对多 分页查询   主表从表都有查询条件 【mybatis】count 统计+JSON查询
		
mybatis实现 主从表 left join 1:n 一对多 分页查询 主表从表都有查询条件+count 需求: ======================================= ...
 - Atitit.列表页and查询条件的最佳实践(1)------设定搜索条件and提交查询and返回json数据
		
Atitit.列表页and查询条件的最佳实践(1)------设置查询条件and提交查询and返回json数据 1. 1. 配置条件字段@Conditional 1 1 2. 2. 配置条件字段显示类 ...
 - Python 进行查询日志查询条件分析
		
任务:crm日志的查询条件 每次是哪几个字段查,有几种组合 ,统计每种组合查询的量 日志样例: -- ::] -- ::] 查询条件:query查询条件可以多个,用|and|分割. 步骤: 1.正则 ...
 - MongoDB小结19 - find【查询条件$all】
		
利用all来查询所以满足的匹配项,已知数据库有这些数据 db.user.find({},{"_id":0}) { "fruit" : [ "apple ...
 - Thinkphp查询 1.查询方式 2.表达式查询 3.快捷查询 4.区间查询 5.组合查询 6.统计查询 7.动态查询 8.SQL 查询
		
1.使用字符串作为条件查询 $user = M('User'); var_dump($user->where('id=1 AND user="蜡笔小新"')->sele ...
 
随机推荐
- 初识Java(2) 变量与数据类型
			
一. 变量 1.变量是内存中的一个标识符号,用于存储数据 2.变量命名规则 1) 必须以字母.下划线 _ .美元符号 $ 开头 2) 变量中,可以包括数字 3) 变量中,不能出现特殊的符号,空格 4 ...
 - 本地修改js代码并时时生效的解决办法
			
js作为客户端语言(当然它也可以作服务端语言),非常强悍,一般情况下,我们都是在开发阶段不停的改,然后上线之后就作为稳定运行的代码. 然而有时候可能因为js写得有问题,导致上线后,某些功能无法使用,这 ...
 - 微信小程序开发 -- 02
			
微信小程序开发 --02 微信小程序在开发中,难度系数不是很大,其中应用的技术也是web开发中常用的技术,虽然在微信开发者工具中的叫法与常见的web开发的叫法不太一样. 首先,在微信小程序开发中,代码 ...
 - Context源码分析
			
我们做安卓开发,时时都在和Context打交道,那么Context到底是什么?有什么作用?如何与Application,Activity,Service等实例发生联系的?等等 Context是什么? ...
 - ajax基础知识、用ajax做登录页面、用ajax验证用户名是否可用、ajax动态调用数据库
			
1.ajax的基础知识 ajax是结合了jquery.php等几种技术延伸出来的综合运用的技术,不是新的内容.ajax也是写在<script>标签里面的. 如果使用ajax一定是要有1个处 ...
 - SQL 和 .NET Framework 数据类型对应表
			
SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework) varbinary SqlBytes, S ...
 - 解决(防止)DDOS攻击的另一种思想
			
本方案适合作最后的处理方案. 在服务器遭到DDOS攻击后,防火墙.高防盾或者其他的方案都已经失去了效力,这时运维人员无任何方案可以处理,并且只能任由DDOS攻击或关闭服务器时,该方案可以有限的抵挡大部 ...
 - js移动端/H5同时选择多张图片上传并使用canvas压缩图片
			
最近在做一个H5的项目,里边涉及到拍照上传图片的功能以及识别图片的功能,这里对识别图片的功能不做赘述,不属本文范畴.我在做完并上线项目后,同事跟我提了一个要求是可不可以同时选择多张图片上传,我做的时候 ...
 - [编织消息框架][netty源码分析]7 Unsafe 实现类NioSocketChannelUnsafe职责与实现
			
Unsafe 是channel的内部接口,从书写跟命名上看是不公开给开发者使用的,直到最后实现NioSocketChannelUnsafe也没有公开出去 public interface Channe ...
 - PHPCMS V9表单向导调用及分页
			
参考资料如下:v9_form_tlj为你的表单数据表,`flqh`,`title`,`sj`,`username`,`datetime` 为你表单内的字段,page="$_GET" ...