struts2 hibernate分页.docx
《struts2 hibernate分页.docx》由会员分享,可在线阅读,更多相关《struts2 hibernate分页.docx(15页珍藏版)》请在冰豆网上搜索。
![struts2 hibernate分页.docx](https://file1.bdocx.com/fileroot1/2023-1/23/ba78a253-f41b-4daa-8ee8-5e34c88ed680/ba78a253-f41b-4daa-8ee8-5e34c88ed6801.gif)
struts2hibernate分页
1).针对网上一些struts2分页的例子不完整,代码混乱繁琐,我特意写了一个分页的小例子,供大家参考,如果程序有什么纰漏,请指出。
开发环境:
eclipse3.2+myeclipse5.5
mysql5.0
tomcat5.5
Dreamweaver2004
2)建库,并导入脚本
这里给大家介绍一个mysql客户端工具--SQLyog,非常好用。
----------------------------------------------------admin.sql--------------------------------------------------
/*
SQLyogCommunityEdition-MySQLGUIv6.12
MySQL-5.0.37-community-nt:
Database-test
把这段脚本导入到mysql的test库里面(你可以先建一个test库,这样会省去很多麻烦)
*********************************************************************
*/
/*!
40101SETNAMESutf8*/;
/*!
40101SETSQL_MODE=''*/;
createdatabaseifnotexists`test`;
USE`test`;
/*!
40014SET@OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,FOREIGN_KEY_CHECKS=0*/;
/*!
40101SET@OLD_SQL_MODE=@@SQL_MODE,SQL_MODE='NO_AUTO_VALUE_ON_ZERO'*/;
/*Tablestructurefortable`admin`*/
DROPTABLEIFEXISTS`admin`;
CREATETABLE`admin`(
`id`int(11)NOTNULLauto_increment,
`user`char(20)defaultNULL,
`pass`char(20)defaultNULL,
PRIMARYKEY(`id`)
)ENGINE=InnoDBDEFAULTCHARSET=gb2312;
/*Dataforthetable`admin`*/
insertinto`admin`(`id`,`user`,`pass`)values(786432,'天使','#####'),(786433,'天使','#####'),(786434,'天使','#####'),(786435,'天使','#####'),(786436,'天使','#####'),(819200,'天使','#####'),(819201,'天使','#####'),(819202,'天使','#####'),(819203,'天使','#####'),(819204,'天使','#####'),(819205,'wangbacheng','#####'),(851968,'天使','#####'),(851969,'天使','#####'),(851970,'天使','#####'),(851971,'天使','#####'),(851972,'天使','#####');
/*!
40101SET SQL_MODE=@OLD_SQL_MO */;
/*!
40014SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
DE
3)建立数据库连接程序,也就是hibernate相关程序,都可以用eclipse自动生成,这个不用多说
在eclipse中只要引入hibernate核心包和struts2包就可以了
-------------------------------------------------HibernateSessionFactory.java-------------------------------------
packageaction;
importorg.hibernate.HibernateException;
importorg.hibernate.Session;
importorg.hibernate.cfg.Configuration;
/**
*ConfiguresandprovidesaccesstoHibernatesessions,tiedtothe
*currentthreadofexecution.FollowstheThreadLocalSession
*pattern,see {@link http:
//hibernate.org/42.html }.
*/
publicclassHibernateSessionFactory{
/**
*Locationofhibernate.cfg.xmlfile.
*LocationshouldbeontheclasspathasHibernateuses
*#resourceAsStreamstylelookupforitsconfigurationfile.
*Thedefaultclasspathlocationofthehibernateconfigfileis
*inthedefaultpackage.Use#setConfigFile()toupdate
*thelocationoftheconfigurationfileforthecurrentsession.
*/
privatestaticStringCONFIG_FILE_LOCATION="/hibernate.cfg.xml";
privatestaticfinalThreadLocalthreadLocal=newThreadLocal();
privatestaticConfigurationconfiguration=newConfiguration();
privatestaticorg.hibernate.SessionFactorysessionFactory;
privatestaticStringconfigFile=CONFIG_FILE_LOCATION;
static{
try{
configuration.configure(configFile);
sessionFactory=configuration.buildSessionFactory();
}catch(Exceptione){
System.err
.println("%%%%ErrorCreatingSessionFactory%%%%");
e.printStackTrace();
}
}
privateHibernateSessionFactory(){
}
/**
*ReturnstheThreadLocalSessioninstance.Lazyinitialize
*theSessionFactory
ifneeded.
*
*@returnSession
*@throwsHibernateException
*/
publicstaticSessiongetSession()throwsHibernateException{
Sessionsession=(Session)threadLocal.get();
if(session==null||!
session.isOpen()){
if(sessionFactory==null){
rebuildSessionFactory();
}
session=(sessionFactory!
=null)?
sessionFactory.openSession()
:
null;
threadLocal.set(session);
}
returnsession;
}
/**
*Rebuildhibernatesessionfactory
*
*/
publicstaticvoidrebuildSessionFactory(){
try{
configuration.configure(configFile);
sessionFactory=configuration.buildSessionFactory();
}catch(Exceptione){
System.err
.println("%%%%ErrorCreatingSessionFactory%%%%");
e.printStackTrace();
}
}
/**
*Closethesinglehibernatesessioninstance.
*
*@throwsHibernateException
*/
publicstaticvoidcloseSession()throwsHibernateException{
Sessionsession=(Session)threadLocal.get();
threadLocal.set(null);
if(session!
=null){
session.close();
}
}
/**
*returnsessionfactory
*
*/
publicstaticorg.hibernate.SessionFactorygetSessionFactory(){
returnsessionFactory;
}
/**
*returnsessionfactory
*
*sessionfactorywillberebuildedinthenextcall
*/
publicstaticvoidsetConfigFile(StringconfigFile){
HibernateSessionFactory.configFile=configFile;
sessionFactory=null;
}
/**
*returnhibernateconfiguration
*
*/
publicstaticConfigurationgetConfiguration(){
returnconfiguration;
}
}
--------------------------------------------------Admin.java--------------------------------------------------
packageaction;
/**
*AdmingeneratedbyMyEclipsePersistenceTools
*/
publicclassAdminimplementsjava.io.Serializable{
//Fields
privateIntegerid;
privateStringuser;
privateStringpass;
//Constructors
/**defaultconstructor*/
publicAdmin(){
}
/**minimalconstructor*/
publicAdmin(Integerid){
this.id=id;
}
/**fullconstructor*/
publicAdmin(Integerid,Stringuser,Stringpass){
this.id=id;
this.user=user;
this.pass=pass;
}
//Propertyaccessors
publicIntegergetId(){
returnthis.id;
}
publicvoidsetId(Integerid){
this.id=id;
}
publicStringgetUser(){
returnthis.user;
}
publicvoidsetUser(Stringuser){
this.user=user;
}
publicStringgetPass(){
returnthis.pass;
}
publicvoidsetPass(Stringpass){
this.pass=pass;
}
}
-------------------------------------------------------------Admin.xml------------------------------------------
xmlversion="1.0"encoding="utf-8"?
>
DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
"
--
MappingfileautogeneratedbyMyEclipsePersistenceTools
-->
-------------------------------------------------hibernate.cfg.xml--------------------------------------------
xmlversion='1.0'encoding='UTF-8'?
>
DOCTYPEhibernate-configurationPUBLIC
"-//Hibernate/HibernateConfigurationDTD3.0//EN"
"
--GeneratedbyMyEclipseHibernateTools. -->
root
jdbc:
mysql:
//localhost:
3306/test
org.hibernate.dialect.MySQLDialect
Mysql
root
com.mysql.jdbc.Driver
4).建个工具类,把一些方法封装到里面
--------------------------------------------------PagerHelper.java--------------------------------------------
packageaction;
importjava.util.Collection;
importjava.util.Iterator;
importorg.hibernate.HibernateException;
importorg.hibernate.Query;
importorg.hibernate.Session;
importorg.hibernate.Transaction;
/**
*
*@authorlike_dark
*注意:
java包命名的时候不能以”java“命名,例如java.my.xxx;真是奇怪啊
*
*/
publicclassPagerHelper{
publicCollectionfindWithPage(intpageSize,intstartRow)throws
HibernateException{
Collectionadmins=null;
Transactiontx=null;
try{
Sessionsession=HibernateSessionFactory.getSession();
tx= session.beginTransaction();
Queryq=session.createQuery("fromAdmin");
q.setMaxResults(pageSize);
q.setFirstResult(startRow);
admins=q.list();
mit();
}catch(HibernateExceptionhe){
if(tx!
=null){
tx.rollback();
}
throwhe;
}finally{
HibernateSessionFactory.closeSession();
}
returnadmins;
}
publicintgetRows(Stringquery)throws
HibernateException{
//query:
selectcount(*)fromAdmin
inttotalRows=0;
Transactiontx=null;
try{
Sessionsession=HibernateSessionFactory.getSession();
tx=session.beginTransaction();
totalRows=((Long)session.createQuery(query).list().iterator().next()).intValue();
mit();
}catch(HibernateExceptionhe){
if(tx!
=null){
tx.rollback();
}
throwhe;
}finally{
HibernateSessionFactory.closeSession();
}
returntotalRows;
}
publicstaticvoidmain(String[]args){
PagerHelperph=newPagerHelper();
System.out.println("rows:
"+ph.getRows("selectcount(*)fromAdmin"));
}
}
5).struts2相关程序和配置
------------------------------------------