How to calculate minimum in Hibernate using the min() Function

In Hibernate min function is used to calculate the minimum based on a criteria or without criteria. This tutorial will teach you how to calculate the minimum in Hibernate with the help of min() function of Hibernate API.

How to calculate minimum in Hibernate using the min() Function

How to calculate minimum in Hibernate using the min() Function

The min() function of Hibernate API translates it to the SQL query and execute it against database which finally returns the result of the query to the Java program.

In this tutorial we will use the min() function in Hibernate and run it in the Eclipse IDE. Our example code returns the result of min() to a calling program in Java.

The min() function is part of HQL and follows the semantics of Hibernate Query Language.

min() function in HQL returns the smallest value from the selected properties. This function can be simply written with select clause as:

select min(gd.numOfGoodsOrder) from GoodsDealer gd

Above code calculates the minimum of numOfGoodsOrder from the GoodsDealer Entity(corresponding mapped table).

Hibernate allows the different keywords as the SQL to be written with the min() function.

for example : min( [ distinct | all ] object.property )

Example :

Example program discussed here will teach you how to use the HQL min() function in your Hibernate based programs.

In this example at first I have created a table named goodsdealer ( goodsDealerId(int, pk), orderedGoodsName(varchar), numOfGoodsOrder(int), priceOfGoods(int) ) then I have created a POJO / Persistent class named GoodsDealer.java and inserted some values in their respected fields then created a POJO / Persistent class named GoodsDealer.java of which data members will be mapped to the database table by their respective fields using a mapping file created by the name GoodsDealer.hbm.xml. Then created a configuration mapping file by the name hibernate.cfg.xml that provides information to the Hibernate to create a connection pool and required environment setup. Finally created a main class where I shall use the min() function with the select clause.

Complete Code

goodsdealer table

CREATE TABLE `goodsdealer` ( 
`goodsDealerId` int(15) NOT NULL, 
`orderedGoodsName` varchar(15) default NULL, 
`numOfGoodsOrder` int(20) default NULL, 
`priceOfGoods` int(10) default NULL 
)

GoodsDealer.java

package roseindia;

public class GoodsDealer {
private int goodsDealerId;
private int numOfGoodsOrder;
private int totalPrice;
private int priceOfGoods;
private String orderedGoodsName;


public GoodsDealer()
{
super();
}
public GoodsDealer(int totalPrice, int priceOfGoods, int goodsDealerId, int numOfGoodsOrder, String orderedGoodsName)
{
this.totalPrice = totalPrice;
this.priceOfGoods = priceOfGoods;
this.goodsDealerId = goodsDealerId;
this.numOfGoodsOrder = numOfGoodsOrder;
this.orderedGoodsName = orderedGoodsName;
}
public int getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public int getPriceOfGoods() {
return priceOfGoods;
}
public void setPriceOfGoods(int priceOfGoods) {
this.priceOfGoods = priceOfGoods;
}
public int getGoodsDealerId() {
return goodsDealerId;
}
public void setGoodsDealerId(int goodsDealerId) {
this.goodsDealerId = goodsDealerId;
}
public int getNumOfGoodsOrder() {
return numOfGoodsOrder;
}
public void setNumOfGoodsOrder(int numOfGoodsOrder) {
this.numOfGoodsOrder = numOfGoodsOrder;
}
public String getOrderedGoodsName() {
return orderedGoodsName;
}
public void setOrderedGoodsName(String orderedGoodsName) {
this.orderedGoodsName = orderedGoodsName;
}
}

GoodsDealer.hbm.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="roseindia">
<class name= "GoodsDealer" table="goodsdealer">
<id name= "goodsDealerId" type="int" column="goodsDealerId">
<!-- <generator class="increement"/>-->
</id>
<property name="numOfGoodsOrder">
<column name="numOfGoodsOrder"/>
</property>
<property name="orderedGoodsName">
<column name="orderedGoodsName"/>
</property>
<property name="totalPrice">
<column name="totalPrice"/>
</property>
<property name="priceOfGoods">
<column name="priceOfGoods"/>
</property>
</class>

</hibernate-mapping>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.13:3306/data
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>

</hibernate-configuration>

HibernateMinFunction.java

package roseindia;

import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateMinFunction {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static void main(String args[])
{
Session session = null;
try
{
try
{
Configuration cfg= new 
Configuration().addResource("roseindia/GoodsDealer.hbm.xml");
cfg.configure();
serviceRegistry = new 
ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch(Throwable th)
{
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
}
session = sessionFactory.openSession();
Query query = session.createQuery("select min(gd.numOfGoodsOrder) from 
GoodsDealer gd");
Iterator min = query.iterate();
System.out.println("Minimum value of the property numOfGoodsOrder = 
"+min.next());
}
catch(Exception e)
{
System.out.println(e.getMessage());
} 
finally
{
session.close();
}
}
}

Output :

1. goodsdealer table

2. When you will execute the java file HibernateMinFunction.java ( RightClick -> Run As -> Java Application ) an output will displayed on console as :

Download Source Code

Check 1000s of tutorial of Hibernate ORM framework.