Wednesday 24 August 2011

Min() Function

In this section, we will show you, how to use the Min() function. Hibernate supports multiple aggregate functions.

Hibernate Min() Function (Aggregate Functions)

In this section, we will show you, how to use the Min() function. Hibernate supports multiple aggregate functions. When they are used in HQL queries, they return an aggregate value ( such as avg(...), sum(...), min(...), max(...) , count(*), count(...), count(distinct ...), count(all...) ) calculated from property values of all objects satisfying other query criteria. 
Following is a aggregate function (min() function) with their respective syntax.
min( [ distinct | all ] object.property)
The Min() function aggregates the minimum value of the given column. 
Table Name: insurance









IDinsurance_nameinvested_amountinvestement_date
2Life Insurance250000000-00-00 00:00:00
1Givan Dhara20000 2007-07-30 17:29:05
3Life Insurance  5002005-10-15 00:00:00
4Car Insurance   25002005-01-01 00:00:00
5Dental Insurance5002004-01-01 00:00:00
Life Insurance9002003-01-01 00:00:00
Travel Insurance  2000 2005-02-02 00:00:00
Here is the java code to retrieve the minimum value of "invested_amount" column from insurance table:


package roseindia.tutorial.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateHQLMinFunction {

  /**
 * @Vinod Kumar
 */
  public static void main(String[] args) {
  // TODO Auto-generated method stub
  Session sess = null;
  try {
  SessionFactory fact = new 
Configuration
().configure().buildSessionFactory();
  sess = fact.openSession();
  String SQL_QUERY = "select min
(investementAmount) from Insurance insurance"
;
  Query query = sess.createQuery(SQL_QUERY);
  List list = query.list();
  System.out.println("Min
Invested Amount: " 
+ list.get(0));
  }
  catch(Exception e){
  System.out.println(e.getMessage());
  }
  }

}

Output:


log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).log4j:WARN Please initialize the log4j system properly.Hibernate: select min(insurance0_.invested_amount) as col_0_0_ from insurance insurance0_
Min Invested Amount: 500

No comments:

Post a Comment