layui的使用,layui的soulTable的史诗级坑

在项目中添加soulTable这个插件,总的来说,有很多的注意的点需要在这里说明一下:

如果还不知道怎么引入soulTable的小伙伴请看这篇文章:layui-soul-table插件的使用详解
然后就是就需要在你的项目中引入这样几个文件;
在这里插入图片描述
然后在你的数据库配置文件中需要加上以下的一段配置:

<plugins>
        <!-- 配置PageHelper -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="helperDialect" value="mysql"/>
            <property name="pageSizeZero" value="true"/>
        </plugin>
        <plugin interceptor="com.zhiruan.base.util.DBDriverInterceptor"/>
    </plugins>

这里的配置得根据实际的需求去配置比如我的就是这样的配置的:
在这里插入图片描述

在文章的结尾我会将这几个Java文件给出来,这几个文件的作用就是配合soulTable来实现筛选,具体怎么实现的我也讲不清楚,前台会将你筛选操作编程一个个的条件,传值给后台,后台通过HashMap<String,Object>接收条件,并且在原来的sql语句的基础上进行sql语句拼接实现查询。

Controller层

@RequestMapping(value = "/getSoulZZ_ZZML")
    public void getSoulZZ_ZZML(HttpServletRequest request, HttpServletResponse response,SoulPage<HashMap<String,Object>> soulPage) {
    	JsonUtil out = new JsonUtil(request, response);
    	out.outObjString(zz_ZZMLService.getSoulZZ_ZZML(soulPage));
    }

注意一定要用SoulPage<HashMap<String,Object>> soulPage接收前台传递的数据

Service层

public Object getSoulZZ_ZZML(SoulPage<HashMap<String, Object>> soulPage) {
		return soulPage.setData(zz_ZZMLDao.getSoulZZ_ZZML(soulPage));
	}

Dao层

List<HashMap<String, Object>> getSoulZZ_ZZML(SoulPage<HashMap<String, Object>> soulPage);

XML的Sql

<select id="getSoulZZ_ZZML" resultType="java.util.HashMap">
    	 SELECT t.*,b.CCLJ from ZZ_ZZML t left JOIN zz_zzmb b on t.ZZLXDM=b.ZZLXDM
</select>

这时候报了这样的一个错:

 Every derived table must have its own alias

我的数据库是Mysql的,到底是怎么一回事呢?原来是这个代码可以支持Oracle和Mysql两种的数据库。在这个文件SoulTableInterceptor.java有一个参数为dbType,是用来判断数据库为Oracle还是Mysql的,会根据数据库的类别进行mysql语句的拼接。具体的代码在351行。

    @Override
    public void setProperties(Properties properties) {
        this.dbType = properties.getProperty("dbType");
        if (StringUtils.isEmpty(dbType)) {
        	dbType = DB_DIALECT.MYSQL.name();
        }
    }

下面给出这几个java代码

SoulTableInterceptor.java

package com.zhiruan.base.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.RowBounds;

import com.sun.istack.internal.logging.Logger;

/**
 *  tableFilter的mybatis拦截器
 *  支持:
 *  1、表头筛选
 *  2、分页
 *  3、目前支持数据库:mysql、oracle
 * @author Yelog
 * @date 2019-03-16 22:48
 * @version 1.0
 */
@Intercepts({@Signature(type= StatementHandler.class,method="prepare",args={Connection.class,Integer.class})})
public class SoulTableInterceptor implements Interceptor {
    public static Logger log = Logger.getLogger(SoulTableInterceptor.class);
    private String dbType;

	private enum DB_DIALECT {ORACLE, MYSQL};

    public String getDbType() {
		return dbType;
	}
    //这里的dbType设置请参考在351行
	public void setDbType(String dbType) {
		this.dbType = dbType;
	}

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
        //通过MetaObject优雅访问对象的属性,这里是访问statementHandler的属性
        MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY, new DefaultReflectorFactory());
        //先拦截到RoutingStatementHandler,里面有个StatementHandler类型的delegate变量,其实现类是BaseStatementHandler,然后就到BaseStatementHandler的成员变量mappedStatement
        MappedStatement mappedStatement = (MappedStatement)metaObject.getValue("delegate.mappedStatement");
        // 配置文件中SQL语句的ID
        BoundSql boundSql = statementHandler.getBoundSql();
        // 原始的SQL语句
        String sql = boundSql.getSql();
        // 检测未通过,不是select语句
        if (!checkIsSelectFalg(sql)) {
            return invocation.proceed();
        }
        if (boundSql.getParameterObject() instanceof Map || boundSql.getParameterObject() instanceof SoulPage) {
            SoulPage soulPage = null;
            if (boundSql.getParameterObject() instanceof SoulPage) {
                soulPage = (SoulPage) boundSql.getParameterObject();
            } else {
                Map<?,?> parameter = (Map<?,?>)boundSql.getParameterObject();
                for (Object key : parameter.keySet()) {
                    if (parameter.get(key) instanceof SoulPage) {
                        soulPage = (SoulPage) parameter.get(key);
                    }
                }
            }

            // 没有 soulPage 不需要拦截
            if(soulPage != null) {
                if (soulPage.isColumn()) {
                    // 排序
                    return invocation.proceed();
                } else {
                    Map<String, String> fieldMap = new HashMap<>();
                    if (mappedStatement.getResultMaps().get(0).getResultMappings().size()>0) {
                        for (ResultMapping resultMapping : mappedStatement.getResultMaps().get(0).getResultMappings()) {
                            fieldMap.put(resultMapping.getProperty(),resultMapping.getColumn());
                        }
                    }
                    /**
                     * 分页
                     */
                    StringBuffer filterSql = new StringBuffer("select * from (" + sql + ") A WHERE");
                    // 获取前端指定类型
                    Map<String, Map<String, String>> typeMap = soulPage.getTypeMap();
					List<FilterSo> filterSos = soulPage.getFilterSos();
					if (filterSos != null) {
                        filterSos.forEach(filterSo->{
                            handleFilterSo(filterSo, typeMap, fieldMap, filterSql);
                        });
                    }
					if (StringUtils.endsWith(filterSql, "WHERE")) {
					    filterSql.setLength(0);
					    filterSql.append("select * from (").append(sql).append(") A");
                    }

                    // 排序
                    if (StringUtils.isNotBlank(soulPage.getField())) {
                        filterSql.append(" order by ").append(fieldMap.size() > 0 ? fieldMap.get(soulPage.getField()) : soulPage.getField()).append(" ").append(soulPage.getOrder());
                    }

                    if (soulPage.getLimit()==100000000) {
                        metaObject.setValue("delegate.boundSql.sql",filterSql.toString());
                    } else {
                        // 设置总数
                        soulPage.setCount(getTotle(invocation, metaObject, filterSql.toString()));

                        // 改造后带分页查询的SQL语句 ORACLE 版
                        String pageSql;

                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            pageSql = "select * from (select * from ( select A.*,ROWNUM AS SOULROWNUM from ("
                                    + filterSql.toString() + " ) A) where SOULROWNUM <= " + (soulPage.getOffset() + soulPage.getLimit()) + ") where SOULROWNUM > " + soulPage.getOffset();
                        } else {
                            //改造后带分页查询的SQL语句 MYSQL版
                            pageSql = "select * from (" + filterSql.toString() + " ) A limit " + soulPage.getOffset() + ", " + soulPage.getLimit();
                        }
                        metaObject.setValue("delegate.boundSql.sql",pageSql);
                    }

                    // 采用物理分页后,就不需要mybatis的内存分页了,所以重置下面的两个参数
                    metaObject.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
                    metaObject.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
                }
            }
        }

        return invocation.proceed();
    }

    /**
     * 处理表头筛选数据
     *
     * @author Yelog
     * @date 2019-03-16 22:52
     * @param filterSo
     * @param typeMap
     * @param fieldMap
     * @param filterSql
     * @return void
     */
    private void handleFilterSo(FilterSo filterSo, Map<String, Map<String, String>> typeMap, Map<String, String> fieldMap, StringBuffer filterSql) {
        if (!StringUtils.endsWith(filterSql, "(") && !StringUtils.endsWith(filterSql, "WHERE")) {
            filterSql.append(StringUtils.isBlank(filterSo.getPrefix())?" and":" "+filterSo.getPrefix());
        }

        String field = fieldMap.size()>0?fieldMap.get(filterSo.getField()):filterSo.getField();
        String value = filterSo.getValue();
        switch (filterSo.getMode()) {
            case "in":
                if (filterSo.getValues()==null || filterSo.getValues().size()==0) {
                    filterSql.append(" 1=1");
                    break;
                }
                switch (typeMap.get(field)==null?"":typeMap.get(field).get("type")) {
                    case "date":
						if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(" to_char(");
						} else {
                            filterSql.append(" DATE_FORMAT(");
						}

						filterSql.append(field)
                                .append(", '");
                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(typeMap.get(field).get("value").replaceAll("HH", "HH24").replaceAll("mm", "mi"));
                        } else {
                            filterSql.append(typeMap.get(field).get("value")
                                    .replaceAll("yyyy", "%Y")
                                    .replaceAll("MM", "%m")
                                    .replaceAll("dd", "%d")
                                    .replaceAll("HH", "%H")
                                    .replaceAll("mm", "%i")
                                    .replaceAll("ss", "%s"));
                        }

                        filterSql.append("') in ('")
                                .append(StringUtils.join(filterSo.getValues(), "','"))
                                .append("')");
                        break;
                    default:
                        if (StringUtils.isBlank(filterSo.getSplit())) {
                            filterSql.append(" ")
                                    .append(field)
                                    .append(" in ('")
                                    .append(StringUtils.join(filterSo.getValues(), "','"))
                                    .append("')");
                        } else {
                            //todo 兼容value值内包含正则特殊字符
                            if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                                filterSql.append(" regexp_like(")
                                        .append(field)
                                        .append(", '");
                                for (String filterSoValue : filterSo.getValues()) {
                                    filterSql.append("("+filterSo.getSplit()+"|^){1}"+filterSoValue+"("+filterSo.getSplit()+"|$){1}|");
                                }
                                filterSql.deleteCharAt(filterSql.length()-1);
                                filterSql.append("')");
                            } else {
                                filterSql.append(" ")
                                        .append(field)
                                        .append(" regexp '(");
                                for (String filterSoValue : filterSo.getValues()) {
                                    filterSql.append("("+filterSo.getSplit()+"|^){1}"+filterSoValue+"("+filterSo.getSplit()+"|$){1}|");
                                }
                                filterSql.deleteCharAt(filterSql.length()-1);
                                filterSql.append(")+'");
                            }
                        }

                        break;
                }
                break;
            case "condition":
                if (StringUtils.isBlank(filterSo.getType()) || ((!"null".equals(filterSo.getType()) && !"notNull".equals(filterSo.getType())) && StringUtils.isBlank(filterSo.getValue()))) {
                    filterSql.append(" 1=1");
                    break;
                }
                filterSql.append(" ");
                filterSql.append(field);
                switch (filterSo.getType()) {
                    case "eq":
                        filterSql.append(" = '").append(value).append("'");
                        break;
                    case "ne":
                        filterSql.append(" != '").append(value).append("'");
                        break;
                    case "gt":
                        filterSql.append(" > '").append(value).append("'");
                        break;
                    case "ge":
                        filterSql.append(" >= '").append(value).append("'");
                        break;
                    case "lt":
                        filterSql.append(" < '").append(value).append("'");
                        break;
                    case "le":
                        filterSql.append(" <= '").append(value).append("'");
                        break;
                    case "contain":
                        filterSql.append(" like '%").append(value).append("%'");
                        break;
                    case "notContain":
                        filterSql.append(" not like '%").append(value).append("%'");
                        break;
                    case "start":
                        filterSql.append(" like '").append(value).append("%'");
                        break;
                    case "end":
                        filterSql.append(" like '%").append(value).append("'");
                        break;
                    case "null":
                        filterSql.append(" is null");
                        break;
                    case "notNull":
                        filterSql.append(" is not null");
                        break;
                    default:break;
                }
                break;
            case "date":
                filterSql.append(" ");
                filterSql.append(field);
                switch (filterSo.getType()) {
                    case "yesterday":
                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(" between trunc(sysdate - 1) and trunc(sysdate)-1/(24*60*60) ");
                        } else {
                            filterSql.append(" between date_add(curdate(), interval -1 day) and date_add(curdate(),  interval -1 second) ");
                        }
                        break;
                    case "thisWeek":
                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(" between trunc(sysdate - to_char(sysdate-2,'D')) and trunc(sysdate - to_char(sysdate-2,'D') + 7)-1/(24*60*60) ");
                        } else {
                            filterSql.append(" between date_add(curdate(), interval - weekday(curdate()) day) and date_add(date_add(curdate(), interval - weekday(curdate())+7 day), interval -1 second) ");
                        }
                        break;
                    case "lastWeek":
                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(" between trunc(sysdate - to_char(sysdate-2,'D') - 7) and trunc(sysdate - to_char(sysdate-2,'D'))-1/(24*60*60) ");
                        } else {
                            filterSql.append(" between date_add(curdate(), interval - weekday(curdate())-7 day) and date_add(date_add(curdate(), interval - weekday(curdate()) day), interval -1 second) ");
                        }
                        break;
                    case "thisMonth":
                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(" between trunc(sysdate, 'mm') and trunc(last_day(sysdate)+1)-1/(24*60*60) ");
                        } else {
                            filterSql.append(" between date_add(curdate(), interval - day(curdate()) + 1 day) and DATE_ADD(last_day(curdate()), interval 24*60*60-1 second) ");
                        }
                        break;
                    case "thisYear":
                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(" between trunc(sysdate, 'yyyy') and to_date(to_char(sysdate,'yyyy')||'-12-31 23:59:59', 'yyyy-mm-dd hh24:mi:ss') ");
                        } else {
                            filterSql.append(" between date_sub(curdate(),interval dayofyear(now())-1 day) and str_to_date(concat(year(now()),'-12-31 23:59:59'), '%Y-%m-%d %H:%i:%s') ");
                        }

                        break;
                    case "specific":
                        if (DB_DIALECT.ORACLE.name().equalsIgnoreCase(dbType)) {
                            filterSql.append(" between to_date('").append(filterSo.getValue()).append("', 'yyyy-mm-dd') and to_date('").append(filterSo.getValue()).append("', 'yyyy-mm-dd')+1-1/(24*60*60) ");
                        } else {
                            filterSql.append(" between str_to_date('").append(filterSo.getValue()).append("', '%Y-%m-%d') and str_to_date(concat('").append(filterSo.getValue()).append("',' 23:59:59'), '%Y-%m-%d %H:%i:%s') ");
                        }
                        break;
                    case "all":
                    default:
                        filterSql.delete(filterSql.lastIndexOf(" "), filterSql.length());
                        filterSql.append(" 1=1");
                        break;
                }
                break;
            case "group":
                filterSql.append(" (");
                if (filterSo.getChildren().size()>0) {
                    filterSo.getChildren().forEach(f->{
                        handleFilterSo(f, typeMap, fieldMap ,filterSql);
                    });
                } else {
                    filterSql.append(" 1=1");
                }
                filterSql.append(" )");
            default:break;
        }


	}

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.dbType = properties.getProperty("dbType");
        if (StringUtils.isEmpty(dbType)) {
        	dbType = DB_DIALECT.MYSQL.name();
        }
    }

    /**
     * 获取当前sql查询的记录总数
     *
     * @author Yelog
     * @date 2019-03-16 22:53
     * @param invocation
     * @param metaObject
     * @param sql
     * @return int
     */
    private int getTotle(Invocation invocation, MetaObject metaObject, String sql) throws SQLException {
        Connection connection = (Connection)invocation.getArgs()[0];
        // 查询总条数的SQL语句
        String countSql = "select count(*) from (" + sql + ") a";
        //执行总条数SQL语句的查询
        PreparedStatement countStatement = connection.prepareStatement(countSql);
        获取参数信息即where语句的条件信息,注意上面拿到的sql中参数还是用?代替的
        ParameterHandler parameterHandler = (ParameterHandler) metaObject.getValue("delegate.parameterHandler");
        parameterHandler.setParameters(countStatement);
        ResultSet rs = countStatement.executeQuery();

        if(rs.next()) {
            return rs.getInt(1);
        }
        return 0;
    }

    /**
     * 判断是否是select语句,只有select语句,才会用到分页
     *
     * @author Yujie Yang
     * @date 2019-03-16 22:55
     * @param sql
     * @return boolean
     */
    private boolean checkIsSelectFalg(String sql) {
        String trimSql = sql.trim();
        int index = trimSql.toLowerCase().indexOf("select");
        int index1 = trimSql.toLowerCase().indexOf("with");
        return index == 0 || index1 == 0;
    }


}

SoulPage.java

package com.zhiruan.base.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * 封装table查询数据
 *
 * @author Yujie Yang
 * @date 2018/7/17 18:42
 * @return
 */
public class SoulPage<T> {

    /**
     * layui表格必须参数⬇⬇⬇⬇⬇⬇
     */
    private Integer code = 0;
    private String msg = "";
    /**
     * 总记录
     */
    private Integer count;
    /**
     * 显示的记录
     */
    private List<T> data;

    /**
     * 请求条件
     */
    @JsonIgnore
    private T obj;
    /**
     * 查询条件
     */
    @JsonIgnore
    private Map<String, Object> condition = new HashMap<>();

    /**
     * 请求参数⬇⬇⬇⬇⬇⬇
     */

    /**
     * 当前页 从1开始
     */
    @JsonIgnore
    private Integer page=1;
    /**
     * 页大小
     */
    @JsonIgnore
    private Integer limit=100000000;

    /**
     * 查询列数据
     */
    @JsonIgnore
    private String columns;

    /**
     * 表格列类型
     */
    @JsonIgnore
    private String tableFilterType;
    /**
     * 筛选信息
     */
    @JsonIgnore
    private String filterSos;

    /**
     * 排序信息
     */
    @JsonIgnore
    private String field;
    @JsonIgnore
    private String order = "asc";

    public SoulPage () {

    }
    public SoulPage (Integer page, Integer limit) {
        this.page = page;
        this.limit = limit;
    }

    public List<FilterSo> getFilterSos() {
        return JSON.parseArray(filterSos, FilterSo.class);
    }

    public void setFilterSos(String filterSos) {
        this.filterSos = filterSos;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public List<T> getData() {
        return data;
    }

    public Object setData(List<T> data) {
        if (isColumn()) {
            Map<String, Map<String, String>> typeMap = getTypeMap();
            Map<String, Set<String>> columnMap = new HashMap<>();
            for (T datum : data) {
                for (String column : getColumns()) {
                    columnMap.computeIfAbsent(column, k -> new HashSet<>());
                    Object columnObject = null;
                    if (datum instanceof Map) {
                        columnObject = ((Map<String, ?>)datum).get(column);
                    } else {
                        try {
                            columnObject = ReflectHelper.getValueByFieldName(datum, column);
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    if (columnObject != null) { //空值不展示
                        columnMap.get(column).add(getFormatValue(typeMap, column, columnObject));
                    }
                }
            }
            Map<String, List<String>> columnSortMap = new HashMap<>();
            Iterator<Map.Entry<String, Set<String>>> it = columnMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Set<String>> entry = it.next();
                ArrayList<String> list = new ArrayList<>(entry.getValue());
                columnSortMap.put(entry.getKey(), list);
            }
            return columnSortMap;
        } else {
            this.data = data;
            return this;
        }
    }

    public T getObj() {
        return obj;
    }

    public void setObj(T obj) {
        this.obj = obj;
    }

    public Integer getPage() {
        return page;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getLimit() {
        return limit;
    }

    public void setLimit(Integer limit) {
        this.limit = limit;
    }

    public int getOffset() {
        return (page - 1) * limit;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public List<String> getColumns() {
        return StringUtils.isNotBlank(columns)? JSON.parseArray(columns, String.class):new ArrayList<>();
    }

    public void setColumns(String columns) {
        this.columns = columns;
    }

    public String getTableFilterType() {
        return tableFilterType;
    }

    public void setTableFilterType(String tableFilterType) {
        this.tableFilterType = tableFilterType;
    }


    /**
     * 结构化 Filter type
     * @return
     */
    @JsonIgnore
    public Map<String, Map<String, String>> getTypeMap() {
        Map<String, Map<String, String>> typeMap = new HashMap<>();
        if (StringUtils.isNotEmpty(tableFilterType)) {
            Map<String, String> filterType = JSON.parseObject(tableFilterType, Map.class);
            filterType.forEach((k,v)->{
                Map<String, String> map = new HashMap<>();
                map.put("type", v.substring(0, v.indexOf("[")));
                map.put("value",v.substring(v.indexOf("[")+1, v.indexOf("]")) );
                typeMap.put(k, map);
            });
        }
        return typeMap;
    }

    /**
     * 根据类型转换最终的值
     * @param typeMap
     * @param column
     * @param columnObject
     * @return
     */
    public String getFormatValue (Map<String, Map<String, String>> typeMap, String column, Object columnObject) {
        String columnValue;
        if (typeMap.containsKey(column)) {
            if ("date".equalsIgnoreCase(typeMap.get(column).get("type")) && columnObject instanceof Date) {
                columnValue = dateFormat((Date) columnObject, typeMap.get(column).get("value"));
            } else {
                columnValue = (String) columnObject;
            }
        } else {
            if (columnObject instanceof Date) {
                columnValue = dateFormat((Date) columnObject, null);
            } else {
                columnValue = String.valueOf(columnObject) ;
            }
        }
        return columnValue;
    }

    /**
     * 是否是列查询
     * @return
     */
    public boolean isColumn () {
        return !getColumns().isEmpty();
    }

    public Map<String, Object> getCondition() {
        return condition;
    }

    public void setCondition(Map<String, Object> condition) {
        this.condition = condition;
    }

    private String dateFormat(Date date, String format) {
        if (StringUtils.isBlank(format)) {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        } else {
            return new SimpleDateFormat(format).format(date);
        }
    }
}

ReflectHelper.java

package com.zhiruan.base.util;

import java.lang.reflect.Field;

/**
 * @author Administrator
 *	反射工具
 */
public class ReflectHelper {
	/**
	 * 获取obj对象fieldName的Field
	 * @param obj
	 * @param fieldName
	 * @return
	 */
	public static Field getFieldByFieldName(Object obj, String fieldName) {
		for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
				.getSuperclass()) {
			try {
				return superClass.getDeclaredField(fieldName);
			} catch (NoSuchFieldException e) {
			}
		}
		return null;
	}

	/**
	 * 获取obj对象fieldName的属性值
	 * @param obj
	 * @param fieldName
	 * @return
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static Object getValueByFieldName(Object obj, String fieldName)
			throws SecurityException, NoSuchFieldException,
			IllegalArgumentException, IllegalAccessException {
		Field field = getFieldByFieldName(obj, fieldName);
		Object value = null;
		if(field!=null){
			if (field.isAccessible()) {
				value = field.get(obj);
			} else {
				field.setAccessible(true);
				value = field.get(obj);
				field.setAccessible(false);
			}
		}
		return value;
	}
}

FilterSo.java

package com.zhiruan.base.util;

import java.util.List;

/**
 * 表头筛选条件实体类
 *
 * @author Yujie Yang
 * @date 2019-01-02 10:00
 */
public class FilterSo {

	/**
	 * 唯一id
	 */
	private Long id;
	/**
	 * 前缀 and、or
	 */
	private String prefix;
	/**
	 * 模式 in、condition、date
	 */
	private String mode;
	/**
	 * 字段名
	 */
	private String field;
	/**
	 * 筛选类型
	 */
	private String type;
	/**
	 * 是否有分隔符
	 */
	private String split;
	/**
	 * 筛选值
	 */
	private String value;
	/**
	 * 筛选值
	 */
	private List<String> values;

	/**
	 * 子组数据
	 */
	private List<FilterSo> children;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getSplit() {
		return split;
	}

	public void setSplit(String split) {
		this.split = split;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public List<String> getValues() {
		return values;
	}

	public void setValues(List<String> values) {
		this.values = values;
	}

	public List<FilterSo> getChildren() {
		return children;
	}

	public void setChildren(List<FilterSo> children) {
		this.children = children;
	}
}

如果你觉得这篇文章对你有帮助,不妨给个赞吧!!!


版权声明:本文为weixin_42334518原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。