|
楼主 |
发表于 2018-6-12 20:12:32
|
显示全部楼层
本帖最后由 String 于 2018-6-12 20:19 编辑
很久之前封装的一套全新查询,实现直接按照条件查询,无需过多代码。
用法:- @RequestMapping(params = "datagrid")
- public void datagrid(XxxEntity xxxEntity, HttpServletRequest request, HttpServletResponse response,
- DataGrid dataGrid) {
- HqlQuery hqlQuery=new HqlQuery(XxxEntity.class, request.getParameterMap(), dataGrid);
- HqlQuery hQuery=DeclareHql.declareHql(hqlQuery);
- Query query=systemService.getSession().createQuery(hqlQuery.getHql());
- DeclareHql.setQuery(hQuery, query).getValue(query, dataGrid);
- TagUtil.datagrid(response, dataGrid);
- }
复制代码 封装类:- /**
- * Copyright 2018 String
- * <p>
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
复制代码import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.jeecgframework.core.common.hibernate.hql.HqlQuery;
import org.jeecgframework.core.common.model.json.DataGrid;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* hql基本封装
*
* @author String
*/
public class DeclareHql {
private static final Logger logger = Logger.getLogger(DeclareHql.class);
private static final String SELECT = "select ";
private static final String AND = " AND ";
private static final String FROM = " from ";
private static final String BLANK = " ";
private static final String DOT = ".";
private static final String LEFT_JOIN = " left join ";
private static final String ORDER_BY = " order by ";
private static final String EQ = " = ";
private static final String LIKE = " like ";
/**
* 时间查询符号
*/
private static final String END = "_end2";
private static final String BEGIN = "_begin1";
private static final SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
/**
* 封装进数据 判断自定义字段排序问题
*
* @return
*/
public void getValue(Query query, DataGrid dataGrid) {
List<?> li = query.list();
int total = li.size();
Class<?> cla = dataGrid.getCla();
boolean flag = true;
if (StringUtils.isNotEmpty(dataGrid.getSort())) {
Method method = getGetMethod(cla, dataGrid.getSort());//获取get方法
if (method != null) {
Column column = method.getAnnotation(Column.class);//获取get方法上注解
if (column == null) {
JoinColumn join = method.getAnnotation(JoinColumn.class);
if (join == null) {
flag = false;
}
}
}
}
List<?> testList = new ArrayList<>();
if (!flag) {
testList = li;
} else
testList = query.setFirstResult((dataGrid.getPage() - 1) * dataGrid.getRows())
.setMaxResults(dataGrid.getRows()).list();
dataGrid.setResults(testList);
dataGrid.setTotal(total);
}
/**
* setquery进值
*
* @param query
* @return
*/
public static DeclareHql setQuery(HqlQuery hqlQuery, Query query) {
if (hqlQuery.getData().size() > 0) {
int num = hqlQuery.getNum();
for (Map<String, Object> obj1 : hqlQuery.getData()) {
Object datatype = obj1.get("model");
Object value = obj1.get("value");
switch (datatype.toString()) {
case "Integer":
query.setInteger(num, Integer.valueOf((String) value));
num++;
break;
case "String":
query.setString(num, value.toString());
num++;
break;
case "Date":
Date date = (Date) value;
query.setDate(num, date);
num++;
break;
default:
break;
}
}
}
return new DeclareHql();
}
/*
* 拼装h q l脚本 h q l
*/
public static HqlQuery declareHql(HqlQuery hqlQuery) {
Class<?> clazz = hqlQuery.getEntityClass();
Map<String, String[]> paramsMap = hqlQuery.getParamsMap();
DataGrid datagrid = hqlQuery.getDataGrid();
hqlQuery.getDataGrid().setCla(clazz);
Field[] declaredFields = clazz.getDeclaredFields();
String obj = clazz.getSimpleName();// 对象名
String otherName = obj.substring(0, 3).toLowerCase();//前缀小写用作hql别名
StringBuffer sb = new StringBuffer();
boolean isPropertyFlag = false;//检验排序字段是否属于实体中的属性 存在更改为 true
sb.append(SELECT + otherName + FROM + obj + BLANK + otherName);
for (Field field : declaredFields) {//存在外键关联的 left join拼接上hql
String type = field.getType().getName();// 类型
String property = field.getName();// 属性名
if (StringUtils.isNotEmpty(datagrid.getSort())) {
if (datagrid.getSort().equals(property))
isPropertyFlag = true;
}
try {
Class<?> cla = Class.forName(type);
if (!isJavaClass(cla)) {// 自定义属性 left join
sb.append(LEFT_JOIN + otherName + DOT + property + BLANK + property);
}
} catch (ClassNotFoundException e) {
// logger.error(e);
// throw new BusinessException("查询出现问题,请联系开发");
continue;
}
}
sb.append(" where 1=1 ");
/**--------添加自定义h q l(注意别名)------------------*/
/**先拼接开发写的hql语句以及query值*/
if (StringUtils.isNotBlank(hqlQuery.getAddHql())) {
int num = 0;
for (char c : hqlQuery.getAddHql().toCharArray()) {
if (c == '?')
num++;
}
hqlQuery.setNum(num);
sb.append(AND);
sb.append(hqlQuery.getAddHql());
}
List<Object> valuelist = new ArrayList<>();
Map<String, Date> dataMap = new HashMap<>();
List<Map<String, Object>> data = new ArrayList<>();
Map<String, Object> map1 = null;
if (hqlQuery.isFlag()) {
sb.append(" and " + otherName + DOT + "sysCompanyCode=? ");
map1 = new HashMap<>();
map1.put("model", "String");
map1.put("value", ResourceUtil.getCompany());
data.add(map1);
}
for (Field field : declaredFields) {
map1 = new HashMap<>();
String type = field.getType().getName();// 类型
String property = field.getName();// 属性名
String beginValue = null, endValue = null; // 判断区间
try {
Class<?> cla = Class.forName(type);
if (type.contains("java.lang") || type.contains("java.math")) {//普通类型
if (paramsMap.containsKey(property)) {
if (!StringUtil.isEmpty(paramsMap.get(property)[0])) {
if (type.equals("java.lang.Integer")) {
sb.append(AND + otherName + DOT + property + EQ + " ?");
map1.put("model", "Integer");
map1.put("value", paramsMap.get(property)[0].trim());
data.add(map1);
} else {
sb.append(AND + otherName + DOT + property + LIKE + " ? ");
map1.put("model", "String");
map1.put("value", "%" + paramsMap.get(property)[0].trim() + "%");
data.add(map1);
}
}
}
} else if (type.contains("java.util.Date")) {//时间类型
Map<String, Object> map2;
if (paramsMap.containsKey(property + BEGIN)) {
beginValue = paramsMap.get(property + BEGIN)[0].trim();
}
if (paramsMap.containsKey(property + END)) {
endValue = paramsMap.get(property + END)[0].trim();
}
if (paramsMap.containsKey(property)) {
beginValue = endValue = paramsMap.get(property)[0].trim();
}
try {
/*if(paramsMap.containsKey(property)){
*//*beginValue = endValue = paramsMap.get(property)[0].trim();*//*
String d = paramsMap.get(property)[0].trim();
if(d!=null&&!"".equals(d)){
sb.append(AND +otherName+DOT+ property + " between ? and ?");
map2 = new HashMap<>();
map2.put("model", "Date");
map2.put("value", time.parse(d + " 00:00:00"));
data.add(map2);
map2 = new HashMap<>();
map2.put("model", "Date");
map2.put("value", time.parse(d + " 23:59:59"));
data.add(map2);
}
}*/
if (org.apache.commons.lang.StringUtils.isNotBlank(beginValue)) {
sb.append(AND + otherName + DOT + property + ">= ? ");
map2 = new HashMap<>();
map2.put("model", "Date");
map2.put("value", time.parse(beginValue + " 00:00:00"));
data.add(map2);
}
if (org.apache.commons.lang.StringUtils.isNotBlank(endValue)) {
sb.append(AND + otherName + DOT + property + "< ? ");
map2 = new HashMap<>();
map2.put("model", "Date");
map2.put("value", time.parse(GetDateUtil.getDay(endValue, 1, "yyyy-MM-dd") + " 00:00:00"));
data.add(map2);
}
} catch (ParseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else if (!isJavaClass(cla)) {
Map<String, String> objMap = obj(paramsMap, property);
if (objMap != null) {
for (Map.Entry<String, String> entry : objMap.entrySet()) {
sb.append(AND + entry.getKey() + LIKE + " ? ");
map1.put("model", "String");
map1.put("value", "%" + entry.getValue() + "%");
data.add(map1);
}
}
}
} catch (ClassNotFoundException e) {
continue;
// logger.error(e);
// throw new BusinessException("代码开了小差,请联系开发");
}
}
hqlQuery.setData(data);
//加进拦截器
String interceptorHql = JeecgDataAutorUtils.loadDataSearchConditonSQLString();
if (StringUtils.isNotEmpty(interceptorHql)) {
if (interceptorHql.substring(0, 4).indexOf("and") == -1)
sb.append(AND);
sb.append(BLANK + interceptorHql);
}
//自定义拦截器hql
//排序
if (datagrid != null)
if (StringUtils.isNotEmpty(datagrid.getSort())) {
if (isPropertyFlag)
sb.append(BLANK + ORDER_BY + otherName + DOT + datagrid.getSort() + BLANK + datagrid.getOrder());
}
hqlQuery.setValueList(valuelist);//query条件
hqlQuery.setDataMap(dataMap);//query时间
hqlQuery.setHql(sb.toString());
return hqlQuery;
}
/**
* 解决前端有自定义的字段 排序问题
*
* @param clazz 实体
* @param dataGrid 已经查询过的datagrid
* @param isEntity 是否是实体
* @return
*/
static String property = null;
@SuppressWarnings("unchecked")
public static List<?> sortList(Class<?> clazz, DataGrid dataGrid, boolean isEntity) {
String sortColumn = dataGrid.getSort();
if (StringUtils.isEmpty(sortColumn)) {
return null;
}
if (sortColumn.indexOf(".") != -1) {
return null;
}
Method method = getGetMethod(clazz, sortColumn);//获取get方法
if (method != null) {
Column column = method.getAnnotation(Column.class);//获取get方法上注解
if (column != null) {
return null;
} else {
JoinColumn join = method.getAnnotation(JoinColumn.class);
if (join != null) {
return null;
}
}
}
property = sortColumn;
List<Map<String, Object>> m = new ArrayList<>();
if (isEntity) {
List<?> list = dataGrid.getResults();
Map<String, Object> map = null;
for (Object c : list) {
map = new HashMap<>();
map = MapBean.BeanToMap(c);
m.add(map);
}
} else {
m = dataGrid.getResults();
}
Collections.sort(m, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
String s1 = (String) o1.get(property);
String s2 = (String) o2.get(property);
Collator collator = Collator.getInstance();
return collator.getCollationKey(s1).compareTo(
collator.getCollationKey(s2));
}
});
if ("desc".equals(dataGrid.getOrder())) {
Collections.reverse(m);
}
//dataGrid.setResults(m);
return m;
}
/**
* java反射bean的get方法
*
* @param objectClass
* @param fieldName
* @return
*/
@SuppressWarnings("unchecked")
public static Method getGetMethod(Class<?> objectClass, String fieldName) {
StringBuffer sb = new StringBuffer();
sb.append("get");
sb.append(fieldName.substring(0, 1).toUpperCase());
sb.append(fieldName.substring(1));
try {
return objectClass.getMethod(sb.toString());
} catch (Exception e) {
}
return null;
}
private static Map<String, String> obj(Map<String, String[]> map, String property) {
for (Map.Entry<String, String[]> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue()[0];
if (key.contains(".") && key.substring(0, key.indexOf(".")).equals(property)) {
if (!StringUtil.isEmpty(value)) {
Map<String, String> result = new HashMap<>();
result.put(key, value);
return result;
}
}
}
return null;
}
/**
* 系统类型
*
* @param clz
* @return
*/
public static boolean isJavaClass(Class<?> clz) {
return clz != null && clz.getClassLoader() == null;
}
} - /**
- * Copyright 2018 String
- * <p>
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
复制代码import org.hibernate.Query;
import org.jeecgframework.core.common.model.json.DataGrid;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 对hql封装
* @author String
*
*/
public class HqlQuery {
private int curPage = 1;// 当前页
private int pageSize = 10;// 默认一页条数
private Class<?> entityClass;//POJO
private Map<String, String[]> paramsMap; //查询的条件
private int total;//总页数
private DataGrid dataGrid;
private List<?> valueList;//条件集合
private Map<String,Date> dataMap;
private String hql;
private Query query;
private Integer num=0;//记录query数据?标示位数
List<Map<String,Object>> data;
private String addHql;
private boolean flag=false;//公司标示
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public String getAddHql() {
return addHql;
}
public void setAddHql(String addHql) {
this.addHql = addHql;
}
public int getCurPage() {
return curPage;
}
public void setCurPage(int curPage) {
this.curPage = curPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public Map<String, String[]> getParamsMap() {
return paramsMap;
}
public void setParamsMap(Map<String, String[]> paramsMap) {
this.paramsMap = paramsMap;
}
public Class<?> getEntityClass() {
return entityClass;
}
public void setEntityClass(Class<?> entityClass) {
this.entityClass = entityClass;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public DataGrid getDataGrid() {
return dataGrid;
}
public void setDataGrid(DataGrid dataGrid) {
this.dataGrid = dataGrid;
}
public List<?> getValueList() {
return valueList;
}
public void setValueList(List<?> valueList) {
this.valueList = valueList;
}
public String getHql() {
return hql;
}
public void setHql(String hql) {
this.hql = hql;
}
public HqlQuery(Class<?> entityClass, Map<String, String[]> paramsMap, DataGrid dataGrid) {
super();
this.entityClass = entityClass;
this.paramsMap = paramsMap;
this.dataGrid = dataGrid;
}
public HqlQuery(Class<?> entityClass, Map<String, String[]> paramsMap, DataGrid dataGrid,Boolean flag) {
super();
this.entityClass = entityClass;
this.paramsMap = paramsMap;
this.dataGrid = dataGrid;
this.flag=flag;
}
public Map<String, Date> getDataMap() {
return dataMap;
}
public void setDataMap(Map<String, Date> dataMap) {
this.dataMap = dataMap;
}
public HqlQuery() {
super();
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
public List<Map<String, Object>> getData() {
return data;
}
public void setData(List<Map<String, Object>> data) {
this.data = data;
}
} - import java.text.DateFormat;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- public class GetDateUtil {
-
- /**
- * 获取周期开始时间
- * @param startTime 上次开始时间
- * @param now 当前时间
- * @param n 周期长度
- * @param unit 周期单位
- * @return 包含当前时间的周期开始时间
- * @throws Exception
- */
- public Date getStartTime(Date startTime,Date now,int n,String unit) throws Exception{
- Calendar cal = Calendar.getInstance();
- Date endTime = new Date();
- if("0".equals(unit)){
- endTime = getHour(startTime, n);
- }else if("1".equals(unit)){
- endTime = getDay(startTime, n);
- }else if("2".equals(unit)){
- endTime = getTheWeekMonday(startTime, n);
- }else if("3".equals(unit)){
- endTime = getTheMonthDay(startTime, n);
- }else{
- endTime = getDay(startTime, n);
- }
- if(startTime.before(now)&&endTime.after(now)){
- cal.setTime(startTime);
- }else{
- startTime.setTime(endTime.getTime());
- startTime = getStartTime(startTime, now, n, unit);
- cal.setTime(startTime);
- }
-
-
- return cal.getTime();
- }
-
- /**
- * 返回某个时间的N小时后时间
- * @param date
- * @param n
- * @return 某小时
- * @throws Exception
- */
- public static Date getHour(Date date,int n) throws Exception{
- Calendar cal = Calendar.getInstance();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
- date = sdf.parse(sdf.format(date));
- cal.setTime(date);
- cal.add(Calendar.HOUR_OF_DAY, n);
-
- return cal.getTime();
- }
- /**
- * 返回某天后N的天日期
- * @param date
- * @param n
- * @return 日期
- * @throws Exception
- */
- public static Date getDay(Date date,int n) throws Exception{
- Calendar cal = Calendar.getInstance();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
- date = sdf.parse(sdf.format(date));
- cal.setTime(date);
- cal.add(Calendar.DAY_OF_MONTH, n);
-
- return cal.getTime();
- }
-
-
- /**
- * 查询n周后周一
- * @param date 当前时间
- * @param n
- * @return 返回n周后周一
- */
- public static Date getTheWeekMonday(Date date,int n) throws Exception{
- Calendar cal = Calendar.getInstance();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
- date = sdf.parse(sdf.format(date));
- cal.setTime(date);
- int i = cal.get(Calendar.DAY_OF_WEEK);
- if(i==Calendar.SUNDAY){
- cal.add(Calendar.WEEK_OF_YEAR, n-1);// 当前日期的下周一
- }else{
- cal.add(Calendar.WEEK_OF_YEAR, n);// 当前日期的下周一
- }
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
-
- return cal.getTime();
- }
-
- /**
- * 返回当前日期的下N月1号
- * @param date 当前日期
- * @return 当前日期的n月后1号
- * @throws Exception
复制代码 |
|