/**
* Hibernate条件查询某些字段,根据需要可以进行分页处理
* @param selectList 要查询的某些字段
* @param orderParamMap <String, Object> key标识哪些按哪些字段查询(用于拼sql),value标识这些字段的值
* @param limitEntry 如果不为null,分页的条件 <Integer,Integer>key标识开始索引,value标识每页记录数
*
*/
@Override
public List<Object> findField(List<String> selectList,
Map<String, Object> paramMap,
Map<String, String> orderParamMap,
Map.Entry<Integer, Integer> limitEntry) {
//判断参数类型,如果不是指定的类型,则抛出异常
if(paramMap != null && !LinkedHashMap.class.equals(paramMap.getClass())){
throw new RuntimeException("参数paramMap必须是LinkedHashMap类型");
}
if(orderParamMap != null && !LinkedHashMap.class.equals(orderParamMap.getClass())){
throw new RuntimeException("参数orderParamMap必须是LinkedHashMap类型");
}
String hql = "";
if(selectList != null && selectList.size() > 0){
hql += " select ";
for(int i = 0; i < selectList.size(); i ++){
if(i > 0){
hql += " , ";
}
hql += " " + selectList.get(i) + " ";
}
}
hql += "from " + GenericUtils.getGenericSuperClass(this.getClass()).getName() + " where 1=1 ";
Map<String, Object> mapCondition = new LinkedHashMap<String, Object>();
if(paramMap != null && paramMap.size() > 0){
Iterator<Map.Entry<String, Object>> iter = paramMap.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, Object> entry = iter.next();
String key = entry.getKey();
Object value = entry.getValue();
Class<?> clazz = value.getClass();
if(clazz == Integer.class || clazz == Double.class || clazz == Long.class){
hql += " and " + key + " = :" + key + " ";
mapCondition.put(key, value);
continue;
}
if(key.endsWith("$")){
key = key.substring(0, key.length()-1);
hql += " and " + key + " = :" + key + " ";
mapCondition.put(key, value);
continue;
}
hql += " and " + key + " like :" + key + " ";
mapCondition.put(key, "%" + value.toString().trim() + "%");
}
}
if(orderParamMap != null && orderParamMap.size() > 0){
hql += " order by ";
Iterator<Map.Entry<String, String>> iter = orderParamMap.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, String> entry = iter.next();
String key = entry.getKey();
String value = entry.getValue();
hql += " " + key + " " + value + " ";
}
}
if(limitEntry != null){
Integer key = limitEntry.getKey();
Integer value = limitEntry.getValue();
if(key != null && value != null){
hql += " limit " + key + ", " + value + " ";
}
}
Query query = getSession().createQuery(hql);
if(mapCondition != null && mapCondition.size() > 0){
Iterator<Map.Entry<String, Object>> iter = mapCondition.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, Object> entry = iter.next();
String key = entry.getKey();
Object value = entry.getValue();
Class<?> clazz = value.getClass();
if(clazz == Integer.class){
query.setInteger(key, (Integer)value);
continue;
}
if(clazz == Double.class){
query.setDouble(key, (Double)value);
continue;
}
if(clazz == Long.class){
query.setLong(key, (Long)value);
continue;
}
query.setString(key, value.toString());
}
}
//使用二级缓存的查询缓存
query.setCacheable(true);
return query.list();
}