JPA Sum Function
In this section, you will learn about sum function of aggregate function of JPQL (Java Persistence Query Language). The sum function to calculate the sum of given fields. Following example displays you how to use the sum function in your jpa application.
JPA Sum Function:
Query query=em.createQuery("SELECT SUM(p.price) FROM Product p"); |
This query calculate the sum of total price of product.
Developing this application, you need the following files:
- Database Table: product
- Model Class: Product.java
- Main Class: JPASumFunctoion.java
Database Table: product
CREATE TABLE `product` ( `id` int(11) NOT NULL auto_increment, `itemName` varchar(50) NOT NULL, `price` double NOT NULL, PRIMARY KEY (`id`) ) |
Model Class: Product.java
/** * */ package roseindia; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * @author Administrator * */ @Entity @Table(name="product") public class Product { @Id @GeneratedValue private int id; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } @Column(name="itemName",length=50,nullable=false) private String itemName; /** * @return the itemName */ public String getItemName() { return itemName; } /** * @param itemName the itemName to set */ public void setItemName(String itemName) { this.itemName = itemName; } @Column(name="price") private double price; /** * @return the price */ public double getPrice() { return price; } /** * @param price the price to set */ public void setPrice(double price) { this.price = price; } } |
Main Class: JPASumFunctoion.java
/** * */ package roseindia; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; /** * @author Administrator * */ public class JPASumFunctoion { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub EntityManagerFactory emf=Persistence.createEntityManagerFactory("jpa"); EntityManager em=emf.createEntityManager(); try{ EntityTransaction entr=em.getTransaction(); entr.begin(); Query query=em.createQuery("SELECT SUM(p.price) FROM Product p"); Number sumOfPrice=(Number) query.getSingleResult(); System.out.println("SUM result:"+sumOfPrice); entr.commit(); } finally{ em.close(); } } } |
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize the log4j system properly. Hibernate: select SUM(product0_.price) as col_0_0_ from product product0_ SUM result:14850.0
|