Hibernate常用的聚合函数

package entity;
//持久化类
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

//HQl查询图书信息
@Entity
@Table
public class HqlQuery {
 private int id;
 private String name;
 private String author;
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAuthor() {
  return author;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 
 public HqlQuery() {
  super();
 }
 public HqlQuery(String name, String author) {
  super(); 
  this.name = name;
  this.author = author;
 }
}

 

//五大函数:

package test;

import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;

public class FunTest {

 public static void main(String[] args) {
  //hcount();
  //hsum();
  //hmax();
  //hmin();
  havg();
 }
 public static void hcount(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction transaction=session.beginTransaction();
  String hql="select count(*) from HqlQuery";
  long n=(Long) session.createQuery(hql).uniqueResult();
  System.out.println("记录数:" + n);
 }
 public static void hsum(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction transaction=session.beginTransaction();
  String hql="select sum(id) from HqlQuery";
  long n=(Long) session.createQuery(hql).uniqueResult();
  System.out.println("和为:" + n);
 }
 public static void hmax(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction transaction=session.beginTransaction();
  String hql="select max(id) from HqlQuery";
  int n=(Integer) session.createQuery(hql).uniqueResult();
  System.out.println("最大id:" + n);
 }
 public static void hmin(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction transaction=session.beginTransaction();
  String hql="select min(id) from HqlQuery";
  int n=(Integer) session.createQuery(hql).uniqueResult();
  System.out.println("最小id:" + n);
 }
 public static void havg(){
  Session session=HibernateUtil.getCurrentSession();
  Transaction transaction=session.beginTransaction();
  String hql="select avg(id) from HqlQuery";
  double n=(Double) session.createQuery(hql).uniqueResult();
  System.out.println("id平均值为:" + n);
 }
}


 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。