使用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將實體映射導入到數據庫中
下面是具體實現的代碼:
- //使用hibernate,實現group by and sum and count
- Session sess = this.getSession(false);
- List list = null;
- if (sess != null) {
- Criteria cri = sess.createCriteria(getModelClass());
- cri.add(Expression.allEq(props));
- // always count id
- ProjectionList projList = Projections.projectionList();
- projList.add(Projections.sum(sum));
- projList.add(Projections.groupProperty(group1));
- projList.add(Projections.groupProperty(group2));
- projList.add(Projections.count(count));
- cri.setProjection(projList);
- list = cri.list();
- }
- listlist = list == null ? new ArrayList() : list;
- return list;
- //使用hibernate,實現group by and sum and count
- List listByGroupSum = dao.getListByGroupSumCP(props);
- Iterator iter = listByGroupSum.iterator();
- if (!iter.hasNext()) {
- System.out.println("No objects to display.");
- }
- while (iter.hasNext()) {
- System.out.println("New object");
- Object[] obj = (Object[]) iter.next();
- for (int i = 0; i < obj.length; i++) {
- System.out.println(obj[i]);
- }
- }
【編輯推薦】