hibernate查询语句实例代码

一、聚集函数的使用:

  • avg(...), sum(...), min(...), max(...)

  • count(*)

  • count(...), count(distinct ...), count(all...)

public DailyStatistics getPreviousDayStatistics(Integer dateNumber) {
String hql = "from DailyStatistics bean where bean.dateNumber=" +
"(select max(ds.dateNumber) from DailyStatistics ds where ds.dateNumber<? and ds.volumeZero=0)";
Query query = getSession().createQuery(hql);
query.setParameter(0, dateNumber);
query.setMaxResults(1);
System.out.println(query.getQueryString());
return (DailyStatistics) query.uniqueResult();
}

二、单属性查询:

List list = session.createQuery("select name from Student").list();
for(Iterator iterator = list.iterator();iterator.hasNext();) {
String name = (String)iterator.next();
System.out.println(name);
}

三、多属性查询:

List list = session.createQuery("select id,name from Student").list();
for(Iterator iterator = list.iterator();iterator.hasNext();) {
Object[] object= (Object[])iterator.next();
//object[0]是id值,object[1]是name值
System.out.println(object[0]+ " "+object[1]);
}

四、返回实体类:

List list = session.createQuery("select new Student(id,name) from Student").list();
for(Iterator iterator = list.iterator();iterator.hasNext();) {
Student student= (Student)iterator.next();
System.out.println(student.getId()+ " "+student.getName());
}

五、多个属性查询:

List list = session.createQuery("select s.id,s.name from Student as s").list();
for(Iterator iterator = list.iterator();iterator.hasNext();) {
Object[] object= (Object[])iterator.next();
System.out.println(object[0]+ " "+object[1]);
} 或 List list = session.createQuery("select id,name from Student s").list();
for(Iterator iterator = list.iterator();iterator.hasNext();) {
Object[] object= (Object[])iterator.next();
System.out.println(object[0]+ " "+object[1]);
}
上一篇:hdu_5793_A Boring Question(打表找规律)


下一篇:利用Java编写简单的WebService实例