关闭

hibernate对象筛选功能(java对象查询)

239人阅读 评论(0) 收藏 举报

筛选功能 

 

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);
		
	}
}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:309543次
    • 积分:8708
    • 等级:
    • 排名:第2263名
    • 原创:1096篇
    • 转载:14篇
    • 译文:0篇
    • 评论:5条
    最新评论