Hibernate DAO類概述
本文向大家介紹Hibernate DAO類,可能好多人還不了解Hibernate DAO類,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會你更多東西。
在Struts分頁有兩種結(jié)構(gòu):
1. 在Action中通過DAO查詢出所有的記錄,然后加到session或request對象中,傳到客戶端,由JSP進(jìn)行分頁。這種方法對于在數(shù)據(jù)量少的時(shí)候很方便,也不影響速度。
2.在Action中每次通過DAO只查詢出一頁的記錄,再傳給JSP頁面。這種結(jié)構(gòu)對于數(shù)據(jù)量大的程序很好,但對于數(shù)據(jù)量小的情況,會增加對服務(wù)器的請求,加大服務(wù)器的負(fù)載。
1).Hibernate DAO類
- package com.jpcf.db.dao;
- import com.jpcf.db.model.*;
- import com.jpcf.db.helper.HibernateUtil;
- import net.sf.hibernate.*;
- import java.util.*;
- import com.jpcf.db.controller.*;
- public class VehiclePropertyDAO {
- public Collection findWithPage(int pageSize, int startRow) throws
- HibernateException {
- Collection vehicleList = null;
- Transaction tx = null;
- try {
- Session session = HibernateUtil.currentSession();
- tx = session.beginTransaction();
- Query q = session.createQuery("from VehicleProperty vp");
- q.setFirstResult(startRow);
- q.setMaxResults(pageSize);
- vehicleList = q.list();
- tx.commit();
- } catch (HibernateException he) {
- if (tx != null) {
- tx.rollback();
- }
- throw he;
- } finally {
- HibernateUtil.closeSession();
- }
- return vehicleList;
- }
- public int getRows(String query) throws
- HibernateException {
- int totalRows = 0;
- Transaction tx = null;
- try {
- Session session = HibernateUtil.currentSession();
- tx = session.beginTransaction();
- totalRows = ((Integer) session.iterate(query).next()).
- intValue();
- tx.commit();
- }
- catch (HibernateException he) {
- if (tx != null) {
- tx.rollback();
- }
- throw he;
- }
- finally {
- HibernateUtil.closeSession();
- }
- return totalRows;
- }
- }
Hibernate DAO類我就貼這些分頁需要的代碼了?!癴rom VehicleProperty vp”也可以用一個(gè)參數(shù)傳進(jìn)來,有興趣的自己改一下吧
2).Action
下面是在Action中用到的代碼:
- public ActionForward queryWithPage(ActionMapping actionMapping,
- ActionForm actionForm
- HttpServletRequest httpServletRequest,
- HttpServletResponse httpServletresponse) {
- Collection clInfos = null;//用于輸出到頁面的記錄集合
- int totalRows;//記錄總行
- VehiclePropertyDAO vehicleDAO = new VehiclePropertyDAO();
- //取得當(dāng)前表中的總行數(shù)
- try {
- totalRows = vehicleDAO.getRows("select count(*) from VehicleProperty");
- } catch (Exception ex) {
- servlet.log(ex.toString());
- return actionMapping.findForward(Constants.FAILURE);
- }
- //通過PagerHelper類來獲取用于輸出到頁面的pager對象
- Pager pager=PagerHelper.getPager(httpServletRequest,totalRows);
- //取出從startRow開始的pageSize行記錄
- try {
- clInfos = vehicleDAO.findWithPage(pager.getPageSize(), pager.getStartRow());
- }
- catch (Exception ex) {
- servlet.log(ex.toString());
- return actionMapping.findForward(Constants.FAILURE);
- }
- //把輸出的記錄集和pager對象保存到request對象中
- httpServletRequest.setAttribute("CLINFOS", clInfos);
- httpServletRequest.setAttribute("PAGER", pager);
- return actionMapping.findForward(Constants.SUCCESS);
- }
查詢語句select count(*) from VehicleProperty 也可以換成你需要的任意的條件(select count(*) from VehicleProperty where ..)
【編輯推薦】