kobexing 2014-07-16
hibernate 查询
hibernate操作的是对象 orm对象关系模型
1.查询一
/** * select street.sname,street.sid from Street as street * 查询得到的是一个 Object[] */ /*List<Object[]> list = session.createQuery("select street.sname,street.sid from Street as street").list(); for (Object[] objects : list) { System.out.println(objects[0]+"+"+objects[1]+"+"); }*/ /** *在Street类里面重写了一个构造方法new Street(street.sname,street.sid) * select new Street(street.sname,street.sid) from Street as street * 查询得到的是一个Street对象 */ List<Street> list = session.createQuery("select new Street(street.sname,street.sid) from Street as street").list();
2. 模糊查询
String hql = "from Street as street where street.sname like ?";//占位符 List<Street> list = session.createQuery(hql).setString(0, "%海%").list();
3.参数查询
String hql = "from Street as street where street.sid>3"; List<Street> list = session.createQuery(hql).list();
4.对象关联查询
String hql = "select provinces from Street street,Provinces provinces where street.provinces=provinces and street.sname='山路'"; List<Provinces> list = session.createQuery(hql).list();
5.分页查询
String hql = "from Street"; Query query = session.createQuery(hql); query.setFirstResult(0);//开始 query.setMaxResults(3);//页面大小 List<Street> list = query.list();
6.函数统计
String hql = "select count(street) from Street as street"; Query query = session.createQuery(hql);
7.排序查询
String hql = "select street from Street as street order by street.sid"; Query query = session.createQuery(hql); List<Street> list = query.list();
8.对象查询
Criteria c = session.createCriteria(Street.class); if(null !=street){ if(null!=street.getSname()){ c.add(Restrictions.like("sname", street.getSname(),MatchMode.ANYWHERE));//模糊查询。查询 sname 中像 street.getSname()的 } if(0!=street.getSid()){ c.add(Restrictions.ge("sid",street.getSid()));//street.getSid()大于等于sid } // if(0!=street.getSid()){ // c.add(Restrictions.le("sid",street.getSid()));//street.getSid()小于等于sid // } } c.addOrder(Order.asc("sid"));//可以增加多个排序规则 // c.addOrder(Order.desc("sid"));//可以增加多个排序规则 hUtil.sessionClose(session); return c.list();
9.查询
Street street = (Street)session.get(Street.class, sid);
10.添加
Provinces provinces = new Provinces(); provinces.setPid(pid); provinces.setPname(pname); session.save(provinces);
11.更新
street = (Street)session.load(Street.class, sid); street.setSname(sname); session.update(street);
12.删除
Street street = (Street)session.get(Street.class, id); session.delete(street);
Hibernate配备了一种非常强大的查询语言,这种语言看上去很像SQL。但是不要被语法结构 上的相似所迷惑,HQL是非常有意识的被设计为完全面向对象的查询,它可以理解如继承、多态 和关联之类的概念。