Hibernate HQL的使用
阿新 • • 發佈:2017-08-20
ber ava 小明 popu tracking 分頁查詢 snippet unique track
2
1、簡單查詢(查詢所有)
Session session=HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx=session.beginTransaction(); List<People> 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<People> 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<People> 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<People> peoples=query.list(); for(People people:peoples){ System.out.println(people.getId()); } tx.commit();
Hibernate HQL的使用