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

筛选功能

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值