package cn.com.oneslife.dao;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class HibernateDAO extends HibernateDaoSupport {
/**
* @param hql
* @param bean
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public String getQuery(String hql, Object bean) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Class<?> cl = bean.getClass();
Field[] fields = cl.getDeclaredFields();
Map<String, Object> listParam = new HashMap<String, Object>();
String fieldName = null;
String regex = "(and)?\\s+[a-zA-Z0-9]*\\.?[a-zA-Z0-9]*\\s+=\\s+:("
+ fieldName + ")";
for (Field field : fields) {
String methodName = "get"
+ field.getName().substring(0, 1).toUpperCase();
methodName += field.getName().substring(1);
Method method = cl.getMethod(methodName);
Object object = method.invoke(bean, new Object[] {});
fieldName = field.getName();
if (null == object) {
hql = hql.replaceAll(regex, "");
} else {
listParam.put(field.getName(), object);
}
}
hql = hql.replaceAll("where", "where true and");
hql = hql.replaceAll("set\\s+and", "set");
Query query = this.getSession().createQuery(hql);
loadParam(query, listParam);
return hql;
}
/**
* @param hql
* @param parameters
* @return
*/
public Query getQuery(String hql, Object... parameters) {
Query query = this.getSession().createQuery(hql);
for (int index = 0; index < parameters.length; index++) {
query.setParameter(index + 1, parameters[index]);
}
return query;
}
/**
* @param query
* @param parameters
* @return
*/
private Query loadParam(Query query, Map<String, Object> parameters) {
Set<Map.Entry<String, Object>> set = parameters.entrySet();
Iterator<Entry<String, Object>> iter = set.iterator();
while (iter.hasNext()) {
Entry<String, Object> entry = iter.next();
query.setParameter(entry.getKey(), entry.getValue());
}
return query;
}
}
将HQL以及参数加载到Query实例中
最新推荐文章于 2025-01-21 11:05:54 发布