Three ways to get the maximum value (max) using Hibernate

Three ways to get the maximum value:

1. Using hsql
Long l = (Long)getSession().createQuery("select max(a.sn) from T a " ).uniqueResult();
System.out.println(c);
Note: To add the alias "a", pay attention to the case of a.ArticleId! Otherwise, an "unexplained attribute" error will occur!

2. Use native sql
sql = "select max(sn) maxid from T";
maxId = (Long)(session.createSQLQuery(sql).addScalar("maxId", Hibernate.INTEGER) ).uniqueResult();
Note: to add the "maxid" scalar

3. Use criteria
Long l = (Long)dbt.getSession().createCriteria(T.class)
.setProjection( Projections.projectionList().add(Projections.max("sn" ) ) ).uniqueResult() ;
Also note that ArticleId is case sensitive!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325775040&siteId=291194637