使用Hibernate代码实例

本文主要讲述了在使用Hibernate时,如何实现group by and sum and count。希望本文能教会你更多东西。

Hibernate是JDBC的升级版,专用连接数据库。它比JDBC简单使用,不需要输入很多的连接数据库代码。提取数据库数据也不用循环提取。使用时的方法为:

1.新建一个Java普通项目

2.创建user library 加入三个地方的jar包:两个hibernate 一个MYSQL驱动

3.创建hibernate配置文件,hibernate.cfg.xml

4.建立实体类user

5.在hibernate文件中寻找eg至底部找出user.hbm.xml映射文件,copy到映射文件所在文件中

6.将映射文件user.hbm.xml部分加入到hibernate.cfg.xml中

7.创建数据库,再利用hibernate将实体映射导入到数据库中

下面是具体实现的代码:

 
 
 
  1. //使用hibernate,实现group by and sum and count  
  2.   Session sess = this.getSession(false);  
  3.   List list = null;  
  4.   if (sess != null) {  
  5.    Criteria cri = sess.createCriteria(getModelClass());  
  6.    cri.add(Expression.allEq(props));  
  7.    // always count id  
  8.    ProjectionList projList = Projections.projectionList();  
  9.    projList.add(Projections.sum(sum));  
  10.    projList.add(Projections.groupProperty(group1));  
  11.    projList.add(Projections.groupProperty(group2));  
  12.    projList.add(Projections.count(count));  
  13.    cri.setProjection(projList);  
  14.    list = cri.list();  
  15.   }  
  16.   listlist = list == null ? new ArrayList() : list;  
  17.   return list;  
  18.  
  19.   //使用hibernate,实现group by and sum and count  
  20.   List listByGroupSum = dao.getListByGroupSumCP(props);  
  21.   Iterator iter = listByGroupSum.iterator();  
  22.   if (!iter.hasNext()) {  
  23.    System.out.println("No objects to display.");  
  24.  
  25.   }  
  26.   while (iter.hasNext()) {  
  27.    System.out.println("New object");  
  28.    Object[] obj = (Object[]) iter.next();  
  29.    for (int i = 0; i < obj.length; i++) {  
  30.     System.out.println(obj[i]);  
  31.    }  
  32.  
  33.   }   
  34.  

【编辑推荐】

  1. 生成Hibernate Mapping文件的分析
  2. 对Hibernate中get()与load()不同点分析
  3. Struts-Spring-Hibernate案例
  4. 简述Hibernate配置连接池
  5. 对Hibernate中get()与load()不同点分析
THE END