1、简单查询(查询所有)
Session session=HibernateUtil.getSessionFactory().getCurrentSession();Transaction tx=session.beginTransaction();List peoples=session.createQuery("from People").list();for(People people:peoples){ System.out.println(people.getName());}tx.commit();
2、依照參数查询
Session session=HibernateUtil.getSessionFactory().getCurrentSession();Transaction tx=session.beginTransaction();//1、依照位置进行參数绑定/*Query query=session.createQuery("from People Where name=?"); query.setString(0,"小明1");*///2、依照參数名进行參数绑定Query query=session.createQuery("from People Where name=:name");query.setString("name","小明1");List peoples=query.list();for(People people:peoples){ System.out.println(people.getName());}tx.commit();
3、分页查询
Session session=HibernateUtil.getSessionFactory().getCurrentSession();Transaction tx=session.beginTransaction();Query query=session.createQuery("from People");query.setFirstResult(0);//设置查询開始的起始位置query.setMaxResults(2);//设置查询的数目List peoples=query.list();for(People people:peoples){ System.out.println(people.getName());}tx.commit();
4、聚集函数的使用
Session session=HibernateUtil.getSessionFactory().getCurrentSession();Transaction tx=session.beginTransaction();//count()Query query=session.createQuery("select count(*) from People");long count=(long) query.uniqueResult();System.out.println(count);tx.commit();//min() max() avg() sum()的使用与count相似
5、in的使用
Session session=HibernateUtil.getSessionFactory().getCurrentSession();Transaction tx=session.beginTransaction();String names[]={"小明1","小明2","小明3"};Query query=session.createQuery("from People where name in (:name)");query.setParameterList("name",names);List peoples=query.list();for(People people:peoples){ System.out.println(people.getId());}tx.commit();