筛选功能
public List findPersonList(int start, int end, Person person) throws HibernateException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
StringBuffer sql = new StringBuffer();
//sql.append("from Person as p where 1=1 ");
//考虑到oracle不支持这种查询方式,所以不要as提高系统的兼容性
sql.append("from Person p where 1=1 ");
Map map = new HashMap();
if(!StringUtils.isEmpty(person.getName())){
sql.append(" and p.name like :name ");
map.put("name", new ParamObject(person,"getName"));
}
if(!StringUtils.isEmpty(person.getPassword())){
sql.append(" and p.password like :password");
map.put("password", new ParamObject(person,"getPassword"));
}
Set params = map.keySet();
Iterator it = params.iterator();
Query q = this.getSession().createQuery(sql.toString());
while(it.hasNext()){
String key = (String)it.next();
ParamObject obj = (ParamObject)map.get(key);
if(obj.execute() instanceof String){
q.setParameter(key, obj.execute());
}
}
//hibernate的分页功能
q.setMaxResults(end);
q.setFirstResult(start);
return q.list();
}
备注:使用HQL查询,查询条件应该是“对象属性”,而不是“表的列名”
package hb.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ParamObject {
private Object instance;
private String method;
public ParamObject(Object instance,String method){
this.instance = instance;
this.method = method;
}
public Object execute() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
Class cls = instance.getClass();
Method md = cls.getMethod(this.method, null);
return md.invoke(instance, null);
}
}