Hibernate 、Hql查询和Criteria查询
HQL查询:
public Object query(String name){ Session s=null; try{ s=HibernateSessionFactory.getSession(); //String hql="from User where name=?"; //Query q=s.createQuery(hql); //q.setString(0, name); String hql="from User where name=:name"; Query q=s.createQuery(hql); q.setString("name", name); //设置分页,使用这两个属性可以实现 分页 // 返回从什么位置开始获取数据 q.setFirstResult(0); //最大获取条数 q.setMaxResults(10); return q.list(); }catch(Exception e){ if(s!=null){ s.close(); } } return null; }
Criteria查询:
public Object queryByName(String name){ Session s=null; try{ s=HibernateSessionFactory.getSession(); Criteria criteria=s.createCriteria(User.class); criteria.add(Restrictions.eq("name", name));// 等于 criteria.add(Restrictions.in("name", new String[]{name})); // in criteria.add(Restrictions.not(Restrictions.in("name", new String[]{name}))); // not in criteria.add(Restrictions.like("name", "%"+name+"%")); // like criteria.add(Restrictions.gt("age", 18)); //大于 criteria.add(Restrictions.lt("age", 12)); //小于 // ...... return criteria.list(); }catch(Exception e){ if(s!=null){ s.close(); } } return null; }
Criteria的其他用法:http://www.cnblogs.com/mabaishui/archive/2009/10/16/1584510.html
更多HQL查询:http://blog.csdn.net/tuke_tuke/article/details/49756313