使用Hibernate代碼實例
本文主要講述了在使用Hibernate時,如何實現(xiàn)group by and sum and count。希望本文能教會你更多東西。
Hibernate是JDBC的升級版,專用連接數(shù)據(jù)庫。它比JDBC簡單使用,不需要輸入很多的連接數(shù)據(jù)庫代碼。提取數(shù)據(jù)庫數(shù)據(jù)也不用循環(huán)提取。使用時的方法為:
1.新建一個Java普通項目
2.創(chuàng)建user library 加入三個地方的jar包:兩個hibernate 一個MYSQL驅(qū)動
3.創(chuàng)建hibernate配置文件,hibernate.cfg.xml
4.建立實體類user
5.在hibernate文件中尋找eg至底部找出user.hbm.xml映射文件,copy到映射文件所在文件中
6.將映射文件user.hbm.xml部分加入到hibernate.cfg.xml中
7.創(chuàng)建數(shù)據(jù)庫,再利用hibernate將實體映射導(dǎo)入到數(shù)據(jù)庫中
下面是具體實現(xiàn)的代碼:
- //使用hibernate,實現(xiàn)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,實現(xiàn)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]);
- }
- }
【編輯推薦】