hibernate如何查找某字段的最大值

2024-11-30 00:35:48
推荐回答(4个)
回答1:

查找某字段的最大值方法:
List results = session.find("select count(*), avg(user.age) from User as user");

ListIterator iterator = results.listIterator();

Object[] rows = (Object[]) iterator.next();

System.out.println("资料笔数: " + rows[0] + "\n平均年龄: " + rows[1]);
例如要查询Problem 中的pid,score,title,totalAccept,totalSubmission,unSee

public class Problem {
private int pid;
private int score;
private int timeLimit;
private int memoryLimit;
private int totalAccept;
private int totalSubmission;
private int unSee;
private String title;
private String description;
private String input;
private String output;

public Problem(int pid, int score,String title, int totalAccept, int totalSubmission,
int unSee) {
super();
this.pid = pid;
this.score = score;
this.totalAccept = totalAccept;
this.totalSubmission = totalSubmission;
this.unSee = unSee;
this.title = title;
}
//省略getter 和 setter
}
查询语句如下
Query query=session.createQuery("select new Problem(pid,score,title,totalAccept,totalSubmission,unSee) from Problem order by pid");
//query.setFirstResult(firstResult); //分页函数
//query.setMaxResults(maxResutl);

List problems=query.list();//返回的还是Problem对象

回答2:

Query q = session.createQuery("select max(c.id) from Event c"); 会获得Event的id字段的最大值

回答3:

Integer maxValue=(Integer)session.createQuery("select max(m.messageId) from Message m ").uniqueResult();
max()返回的是一个Integer类型.

回答4:

select max(查找字段)from Object(对象)