- 浏览: 96733 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
longhaojava:
谢谢,文章很好,对我帮助很大,感谢楼主的分享!
设计模式学习笔记(十七)—Memento备忘录模式 -
枫竹雨:
可以把这个例子发给我吗?我近期在学这方面的东西。谢谢。
我的邮 ...
Struts2+spring2+hibernate3整合方案 -
fengzhizi8584:
学习了~~~~
设计模式学习笔记(一)--Facade外观模式 -
lxtkong-029:
谢谢,郁闷了半天了
Struts2中使用Common-FileUpload实现文件上传 -
女巫の微笑:
条理很清晰
Struts2拦截器学习
Struts2+spring2+hibernate3整合方案
最近闲来无事可做,于是开始学习struts2。Struts2和struts1、webwork2有什么区别我也不说了,网上有很多这方面的资料。以前在项目中从未使用过struts,一直使用spring+hibernate,现在既然学习了Struts,也不能浪费,于是乎开始琢磨着怎么整合这3个框架。整合原理以spring为容器,管理hibernate的DAO和Struts2的Action。
一、 准备工作
Struts2.06+spring2.5+hibernate3.2+jdk6.0+myeclipse6.0+tomcat5.5+mysql5.0
以上是整合的原料。下面以一个注册登陆的例子来开始我们的整合过程。
这个例子很简单,下面是它的sql脚本内容:
CREATE TABLE `user` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(16) NOT NULL,
`email` varchar(30) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8;
二、 开始行动
包结构可以参考下图
图一
图二
图三
1) Struts部分:建立struts.xml和struts.properties
Struts.xml内容如下:
/error.jsp/success.jsp/login.jsp/success.jsp/regist.jsp
Struts.properties内容如下:
struts.devMode=false
struts.enable.DynamicMethodInvocation=true
struts.i18n.reload=true
struts.ui.theme=xhtml
struts.locale=zh_CN
struts.i18n.encoding=UTF-8
struts.objectFactory=spring
struts.objectFactory.spring.autoWire=name
struts.serve.static.browserCache=false
struts.url.includeParams=none
2) 建立User.java和User.hbm.xml、jdbc.properties:
User.java内容如下:
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 23, 2007 1:55:28 PM
*/
package com.firstssh.model;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String username;
private String password;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
User.hbm.xml内容:
jdbc.properties内容如下:
datasource.type=mysql
datasource.driverClassName=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
datasource.username=root
datasource.password=123456
datasource.maxActive=10
datasource.maxIdle=2
datasource.maxWait=120000
datasource.whenExhaustedAction=1
datasource.validationQuery=select 1 from dual
datasource.testOnBorrow=true
datasource.testOnReturn=false
c3p0.acquireIncrement=3
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=900
c3p0.minPoolSize=2
c3p0.maxPoolSize=50
c3p0.maxStatements=100
c3p0.numHelperThreads=10
c3p0.maxIdleTime=600
hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect=org.hibernate.dialect.MySQLMyISAMDialect
hibernate.jdbc.batch_size=25
hibernate.jdbc.fetch_size=50
hibernate.show_sql=true
hibernate.connection.release_mode=after_transaction
3) Spirng部分:为了清晰把Spring的配置文件拆分成以下几部分applicationContext-dao.xml、appliationContext-service.xml、applicationContext-hibernate.xml、action-servlet.xml。
applicationContext-hibernate.xml内容:
WEB-INF/jdbc.properties${datasource.driverClassName}${datasource.url}${datasource.username}${datasource.password}${c3p0.acquireIncrement}${c3p0.initialPoolSize}${c3p0.minPoolSize}${c3p0.maxPoolSize}${c3p0.maxIdleTime}${c3p0.idleConnectionTestPeriod}${c3p0.maxStatements}${c3p0.numHelperThreads}com/firstssh/model/User.hbm.xml${hibernate.dialect}${hibernate.show_sql}
${hibernate.jdbc.fetch_size}
${hibernate.jdbc.batch_size}
PROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIRED,readOnlyPROPAGATION_REQUIRED,readOnlyPROPAGATION_REQUIRED,readOnlyPROPAGATION_REQUIREDPROPAGATION_REQUIRED,readOnlyuserServicetransactionInterceptor
applicationContext-dao.xml内容:
applicationContext-service.xml内容:
action-servlet.xml内容:
以上几个xml文件的内容暂且不要理会,继续往下看,你就自动明白的,不用我解释。
4)日志部分:log4j.properties 、commons-logging.properties
log4j.properties内容:
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${firstssh.root}/WEB-INF/logs/firstssh.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
# OpenSymphony Stuff
log4j.logger.com.opensymphony=INFO
log4j.logger.org.apache.struts2=INFO
# Spring Stuff
log4j.logger.org.springframework=INFO
# Hibernate Stuff
log4j.logger.org.hiberante=INFO
commons-logging.properties
内容:
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
5)web.xml
firstsshthis is a simple examplewebAppRootKeyfirstssh.rootcontextConfigLocation/WEB-INF/applicationContext-*.xml,/WEB-INF/action-servlet.xmllog4jConfigLocation/WEB-INF/log4j.propertiesorg.springframework.web.util.Log4jConfigListenerorg.springframework.web.context.ContextLoaderListenerstruts2org.apache.struts2.dispatcher.FilterDispatcherstruts2/*imgcom.firstssh.servlet.AuthImgimg/authImgencodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingutf-8encodingFilter*.actionencodingFilter*.jsphibernateFilterorg.springframework.orm.hibernate3.support.OpenSessionInViewFilterhibernateFilter*.actiondwr-invokerorg.directwebremoting.servlet.DwrServletdebugtruedwr-invoker/dwr/*10index.jsp401/401.htm403/403.htm404/404.htm500/500.htm
6)dwr.xml
三、 开始编码:
以下是DAO部分的核心代码:
IGenericDao.java内容如下:
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 23, 2007 6:19:21 PM
*/
package com.firstssh.common.dao;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.dao.DataAccessException;
import com.firstssh.common.util.PaginationSupport;
public interface IGenericDao {
public T load(ID id) throws DataAccessException;
public T get(ID id)throws DataAccessException;
public boolean contains(T t) throws DataAccessException;
public void refresh(T t, LockMode lockMode) throws DataAccessException;
public void refresh(T t) throws DataAccessException;
public Serializable save(T t) throws DataAccessException;
public void saveOrUpdate(T t) throws DataAccessException;
public void saveOrUpdateAll(Collection entities)
throws DataAccessException;
public void update(T t, LockMode lockMode) throws DataAccessException;
public void update(T t) throws DataAccessException;
public void delete(T t, LockMode lockMode) throws DataAccessException;
public void delete(T t) throws DataAccessException;
public void deleteAll(Collection entities) throws DataAccessException;
public List find(String queryString, Object value)
throws DataAccessException;
public List find(String queryString, Object[] values)
throws DataAccessException;
public List find(String queryString) throws DataAccessException;
public List list()throws DataAccessException;
public List findByNamedQuery(String queryName)throws DataAccessException ;
public List findByNamedQuery(String queryName, Object value)throws DataAccessException ;
public List findByNamedQuery(String queryName, Object[] values)throws DataAccessException ;
public PaginationSupport findPageByCriteria(
final DetachedCriteria detachedCriteria, final int pageSize,
final int startIndex);
public PaginationSupport findPageByQuery(final String hsql,
final int pageSize, final int startIndex);
}
GenericDao.java内容如下:
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 23, 2007 11:23:56 PM
*/
package com.firstssh.common.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.firstssh.common.util.PaginationSupport;
@SuppressWarnings("unchecked")
public class GenericDao extends HibernateDaoSupport
implements IGenericDao {
private Log logger = LogFactory.getLog(getClass());
protected Class entityClass;
public GenericDao() {
}
protected Class getEntityClass() {
if (entityClass == null) {
entityClass = (Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
logger.debug("T class = " + entityClass.getName());
}
return entityClass;
}
public void saveOrUpdate(T t) throws DataAccessException {
this.getHibernateTemplate().saveOrUpdate(t);
}
public T load(ID id) throws DataAccessException {
T load = (T) getHibernateTemplate().load(getEntityClass(), id);
return load;
}
public T get(ID id) throws DataAccessException {
T load = (T) getHibernateTemplate().get(getEntityClass(), id);
return load;
}
public boolean contains(T t) throws DataAccessException {
return getHibernateTemplate().contains(t);
}
public void delete(T t, LockMode lockMode) throws DataAccessException {
getHibernateTemplate().delete(t, lockMode);
}
public void delete(T t) throws DataAccessException {
getHibernateTemplate().delete(t);
}
public void deleteAll(Collection entities) throws DataAccessException {
getHibernateTemplate().deleteAll(entities);
}
public List find(String queryString, Object value)
throws DataAccessException {
List find = (List) getHibernateTemplate()
.find(queryString, value);
return find;
}
public List find(String queryString, Object[] values)
throws DataAccessException {
List find = (List) getHibernateTemplate().find(queryString,
values);
return find;
}
public List find(String queryString) throws DataAccessException {
return (List) getHibernateTemplate().find(queryString);
}
public void refresh(T t, LockMode lockMode) throws DataAccessException {
getHibernateTemplate().refresh(t, lockMode);
}
public void refresh(T t) throws DataAccessException {
getHibernateTemplate().refresh(t);
}
public Serializable save(T t) throws DataAccessException {
return getHibernateTemplate().save(t);
}
public void saveOrUpdateAll(Collection entities)
throws DataAccessException {
getHibernateTemplate().saveOrUpdateAll(entities);
}
public void update(T t, LockMode lockMode) throws DataAccessException {
getHibernateTemplate().update(t, lockMode);
}
public void update(T t) throws DataAccessException {
getHibernateTemplate().update(t);
}
public List list() throws DataAccessException {
return getHibernateTemplate().loadAll(getEntityClass());
}
public List findByNamedQuery(String queryName)
throws DataAccessException {
return getHibernateTemplate().findByNamedQuery(queryName);
}
public List findByNamedQuery(String queryName, Object value)
throws DataAccessException {
return getHibernateTemplate().findByNamedQuery(queryName, value);
}
public List findByNamedQuery(String queryName, Object[] values)
throws DataAccessException {
return getHibernateTemplate().findByNamedQuery(queryName, values);
}
public PaginationSupport findPageByCriteria(
final DetachedCriteria detachedCriteria, final int pageSize,
final int startIndex) {
return (PaginationSupport) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Criteria criteria = detachedCriteria
.getExecutableCriteria(session);
int totalCount = ((Integer) criteria.setProjection(
Projections.rowCount()).uniqueResult())
.intValue();
criteria.setProjection(null);
List items = criteria.setFirstResult(startIndex)
.setMaxResults(pageSize).list();
PaginationSupport ps = new PaginationSupport(items,
totalCount, pageSize, startIndex);
return ps;
}
}, true);
}
public PaginationSupport findPageByQuery(final String hsql,
final int pageSize, final int startIndex) {
return (PaginationSupport) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(hsql);
int totalCount = query.list().size();
query.setFirstResult(startIndex);
query.setMaxResults(pageSize);
List items = query.list();
PaginationSupport ps = new PaginationSupport(items,
totalCount, pageSize, startIndex);
return ps;
}
}, true);
}
}
呵呵,使用了泛型,以后每建立一个Dao都要建立相应的dao接口和实现类,如本例中的IUserDao和UserDao。
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 24, 2007 12:47:57 AM
*/
package com.firstssh.dao;
import java.util.List;
import com.firstssh.common.dao.IGenericDao;
import com.firstssh.model.User;
public interface IUserDao extends IGenericDao {
public User getUserByName(String username);
public List findAllUser();
public User findUserByNameAndPass(String username, String password);
}
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 24, 2007 12:38:48 AM
*/
package com.firstssh.dao.impl;
import java.util.List;
import com.firstssh.common.dao.GenericDao;
import com.firstssh.dao.IUserDao;
import com.firstssh.model.User;
public class UserDao extends GenericDao implements IUserDao{
public List findAllUser() {
return (List)find("from User");
}
public User findUserByNameAndPass(String username, String password) {
Object[] params=new Object[]{username,password};
List userList=find("from User as user where user.username=? and user.password=? ",params);
if(userList!=null&&userList.size()>=1){
return userList.get(0);
}
return null;
}
public User getUserByName(String username) {
List userList=find("from User as user where user.username=?",username);
if(userList!=null&&userList.size()>=1){
return userList.get(0);
}
return null;
}
}
还有好多文件的代码没有贴出来,我实在不忍心再复制、粘贴下去了(浪费大家那么多时间),有兴趣的可以下载这个例子的源代码(由于这个例子牵涉的jar包比较大我就不把它们放进去了),我想以上这些文件的内容我就不用解释了,因为大家都学过SSH。本人初次整合它们,并没有使用这个整合方案做过项目,一定还有某些方面考虑的还不是太成熟,哪位大侠看了,还请多多批评指正,也希望谁有更好的整合方案,也共享一下,大家共同进步,共同提高!~^_^
最近闲来无事可做,于是开始学习struts2。Struts2和struts1、webwork2有什么区别我也不说了,网上有很多这方面的资料。以前在项目中从未使用过struts,一直使用spring+hibernate,现在既然学习了Struts,也不能浪费,于是乎开始琢磨着怎么整合这3个框架。整合原理以spring为容器,管理hibernate的DAO和Struts2的Action。
一、 准备工作
Struts2.06+spring2.5+hibernate3.2+jdk6.0+myeclipse6.0+tomcat5.5+mysql5.0
以上是整合的原料。下面以一个注册登陆的例子来开始我们的整合过程。
这个例子很简单,下面是它的sql脚本内容:
CREATE TABLE `user` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(16) NOT NULL,
`email` varchar(30) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf-8;
二、 开始行动
包结构可以参考下图
图一
图二
图三
1) Struts部分:建立struts.xml和struts.properties
Struts.xml内容如下:
/error.jsp/success.jsp/login.jsp/success.jsp/regist.jsp
Struts.properties内容如下:
struts.devMode=false
struts.enable.DynamicMethodInvocation=true
struts.i18n.reload=true
struts.ui.theme=xhtml
struts.locale=zh_CN
struts.i18n.encoding=UTF-8
struts.objectFactory=spring
struts.objectFactory.spring.autoWire=name
struts.serve.static.browserCache=false
struts.url.includeParams=none
2) 建立User.java和User.hbm.xml、jdbc.properties:
User.java内容如下:
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 23, 2007 1:55:28 PM
*/
package com.firstssh.model;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String username;
private String password;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
User.hbm.xml内容:
jdbc.properties内容如下:
datasource.type=mysql
datasource.driverClassName=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
datasource.username=root
datasource.password=123456
datasource.maxActive=10
datasource.maxIdle=2
datasource.maxWait=120000
datasource.whenExhaustedAction=1
datasource.validationQuery=select 1 from dual
datasource.testOnBorrow=true
datasource.testOnReturn=false
c3p0.acquireIncrement=3
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=900
c3p0.minPoolSize=2
c3p0.maxPoolSize=50
c3p0.maxStatements=100
c3p0.numHelperThreads=10
c3p0.maxIdleTime=600
hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect=org.hibernate.dialect.MySQLMyISAMDialect
hibernate.jdbc.batch_size=25
hibernate.jdbc.fetch_size=50
hibernate.show_sql=true
hibernate.connection.release_mode=after_transaction
3) Spirng部分:为了清晰把Spring的配置文件拆分成以下几部分applicationContext-dao.xml、appliationContext-service.xml、applicationContext-hibernate.xml、action-servlet.xml。
applicationContext-hibernate.xml内容:
WEB-INF/jdbc.properties${datasource.driverClassName}${datasource.url}${datasource.username}${datasource.password}${c3p0.acquireIncrement}${c3p0.initialPoolSize}${c3p0.minPoolSize}${c3p0.maxPoolSize}${c3p0.maxIdleTime}${c3p0.idleConnectionTestPeriod}${c3p0.maxStatements}${c3p0.numHelperThreads}com/firstssh/model/User.hbm.xml${hibernate.dialect}${hibernate.show_sql}
${hibernate.jdbc.fetch_size}
${hibernate.jdbc.batch_size}
PROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIREDPROPAGATION_REQUIRED,readOnlyPROPAGATION_REQUIRED,readOnlyPROPAGATION_REQUIRED,readOnlyPROPAGATION_REQUIREDPROPAGATION_REQUIRED,readOnlyuserServicetransactionInterceptor
applicationContext-dao.xml内容:
applicationContext-service.xml内容:
action-servlet.xml内容:
以上几个xml文件的内容暂且不要理会,继续往下看,你就自动明白的,不用我解释。
4)日志部分:log4j.properties 、commons-logging.properties
log4j.properties内容:
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
log4j.rootLogger=INFO, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=${firstssh.root}/WEB-INF/logs/firstssh.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
# OpenSymphony Stuff
log4j.logger.com.opensymphony=INFO
log4j.logger.org.apache.struts2=INFO
# Spring Stuff
log4j.logger.org.springframework=INFO
# Hibernate Stuff
log4j.logger.org.hiberante=INFO
commons-logging.properties
内容:
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
5)web.xml
firstsshthis is a simple examplewebAppRootKeyfirstssh.rootcontextConfigLocation/WEB-INF/applicationContext-*.xml,/WEB-INF/action-servlet.xmllog4jConfigLocation/WEB-INF/log4j.propertiesorg.springframework.web.util.Log4jConfigListenerorg.springframework.web.context.ContextLoaderListenerstruts2org.apache.struts2.dispatcher.FilterDispatcherstruts2/*imgcom.firstssh.servlet.AuthImgimg/authImgencodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingutf-8encodingFilter*.actionencodingFilter*.jsphibernateFilterorg.springframework.orm.hibernate3.support.OpenSessionInViewFilterhibernateFilter*.actiondwr-invokerorg.directwebremoting.servlet.DwrServletdebugtruedwr-invoker/dwr/*10index.jsp401/401.htm403/403.htm404/404.htm500/500.htm
6)dwr.xml
三、 开始编码:
以下是DAO部分的核心代码:
IGenericDao.java内容如下:
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 23, 2007 6:19:21 PM
*/
package com.firstssh.common.dao;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.dao.DataAccessException;
import com.firstssh.common.util.PaginationSupport;
public interface IGenericDao {
public T load(ID id) throws DataAccessException;
public T get(ID id)throws DataAccessException;
public boolean contains(T t) throws DataAccessException;
public void refresh(T t, LockMode lockMode) throws DataAccessException;
public void refresh(T t) throws DataAccessException;
public Serializable save(T t) throws DataAccessException;
public void saveOrUpdate(T t) throws DataAccessException;
public void saveOrUpdateAll(Collection entities)
throws DataAccessException;
public void update(T t, LockMode lockMode) throws DataAccessException;
public void update(T t) throws DataAccessException;
public void delete(T t, LockMode lockMode) throws DataAccessException;
public void delete(T t) throws DataAccessException;
public void deleteAll(Collection entities) throws DataAccessException;
public List find(String queryString, Object value)
throws DataAccessException;
public List find(String queryString, Object[] values)
throws DataAccessException;
public List find(String queryString) throws DataAccessException;
public List list()throws DataAccessException;
public List findByNamedQuery(String queryName)throws DataAccessException ;
public List findByNamedQuery(String queryName, Object value)throws DataAccessException ;
public List findByNamedQuery(String queryName, Object[] values)throws DataAccessException ;
public PaginationSupport findPageByCriteria(
final DetachedCriteria detachedCriteria, final int pageSize,
final int startIndex);
public PaginationSupport findPageByQuery(final String hsql,
final int pageSize, final int startIndex);
}
GenericDao.java内容如下:
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 23, 2007 11:23:56 PM
*/
package com.firstssh.common.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.firstssh.common.util.PaginationSupport;
@SuppressWarnings("unchecked")
public class GenericDao extends HibernateDaoSupport
implements IGenericDao {
private Log logger = LogFactory.getLog(getClass());
protected Class entityClass;
public GenericDao() {
}
protected Class getEntityClass() {
if (entityClass == null) {
entityClass = (Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
logger.debug("T class = " + entityClass.getName());
}
return entityClass;
}
public void saveOrUpdate(T t) throws DataAccessException {
this.getHibernateTemplate().saveOrUpdate(t);
}
public T load(ID id) throws DataAccessException {
T load = (T) getHibernateTemplate().load(getEntityClass(), id);
return load;
}
public T get(ID id) throws DataAccessException {
T load = (T) getHibernateTemplate().get(getEntityClass(), id);
return load;
}
public boolean contains(T t) throws DataAccessException {
return getHibernateTemplate().contains(t);
}
public void delete(T t, LockMode lockMode) throws DataAccessException {
getHibernateTemplate().delete(t, lockMode);
}
public void delete(T t) throws DataAccessException {
getHibernateTemplate().delete(t);
}
public void deleteAll(Collection entities) throws DataAccessException {
getHibernateTemplate().deleteAll(entities);
}
public List find(String queryString, Object value)
throws DataAccessException {
List find = (List) getHibernateTemplate()
.find(queryString, value);
return find;
}
public List find(String queryString, Object[] values)
throws DataAccessException {
List find = (List) getHibernateTemplate().find(queryString,
values);
return find;
}
public List find(String queryString) throws DataAccessException {
return (List) getHibernateTemplate().find(queryString);
}
public void refresh(T t, LockMode lockMode) throws DataAccessException {
getHibernateTemplate().refresh(t, lockMode);
}
public void refresh(T t) throws DataAccessException {
getHibernateTemplate().refresh(t);
}
public Serializable save(T t) throws DataAccessException {
return getHibernateTemplate().save(t);
}
public void saveOrUpdateAll(Collection entities)
throws DataAccessException {
getHibernateTemplate().saveOrUpdateAll(entities);
}
public void update(T t, LockMode lockMode) throws DataAccessException {
getHibernateTemplate().update(t, lockMode);
}
public void update(T t) throws DataAccessException {
getHibernateTemplate().update(t);
}
public List list() throws DataAccessException {
return getHibernateTemplate().loadAll(getEntityClass());
}
public List findByNamedQuery(String queryName)
throws DataAccessException {
return getHibernateTemplate().findByNamedQuery(queryName);
}
public List findByNamedQuery(String queryName, Object value)
throws DataAccessException {
return getHibernateTemplate().findByNamedQuery(queryName, value);
}
public List findByNamedQuery(String queryName, Object[] values)
throws DataAccessException {
return getHibernateTemplate().findByNamedQuery(queryName, values);
}
public PaginationSupport findPageByCriteria(
final DetachedCriteria detachedCriteria, final int pageSize,
final int startIndex) {
return (PaginationSupport) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException {
Criteria criteria = detachedCriteria
.getExecutableCriteria(session);
int totalCount = ((Integer) criteria.setProjection(
Projections.rowCount()).uniqueResult())
.intValue();
criteria.setProjection(null);
List items = criteria.setFirstResult(startIndex)
.setMaxResults(pageSize).list();
PaginationSupport ps = new PaginationSupport(items,
totalCount, pageSize, startIndex);
return ps;
}
}, true);
}
public PaginationSupport findPageByQuery(final String hsql,
final int pageSize, final int startIndex) {
return (PaginationSupport) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery(hsql);
int totalCount = query.list().size();
query.setFirstResult(startIndex);
query.setMaxResults(pageSize);
List items = query.list();
PaginationSupport ps = new PaginationSupport(items,
totalCount, pageSize, startIndex);
return ps;
}
}, true);
}
}
呵呵,使用了泛型,以后每建立一个Dao都要建立相应的dao接口和实现类,如本例中的IUserDao和UserDao。
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 24, 2007 12:47:57 AM
*/
package com.firstssh.dao;
import java.util.List;
import com.firstssh.common.dao.IGenericDao;
import com.firstssh.model.User;
public interface IUserDao extends IGenericDao {
public User getUserByName(String username);
public List findAllUser();
public User findUserByNameAndPass(String username, String password);
}
/** *//**
*
* @author flustar
* @version 1.0
* Creation date: Dec 24, 2007 12:38:48 AM
*/
package com.firstssh.dao.impl;
import java.util.List;
import com.firstssh.common.dao.GenericDao;
import com.firstssh.dao.IUserDao;
import com.firstssh.model.User;
public class UserDao extends GenericDao implements IUserDao{
public List findAllUser() {
return (List)find("from User");
}
public User findUserByNameAndPass(String username, String password) {
Object[] params=new Object[]{username,password};
List userList=find("from User as user where user.username=? and user.password=? ",params);
if(userList!=null&&userList.size()>=1){
return userList.get(0);
}
return null;
}
public User getUserByName(String username) {
List userList=find("from User as user where user.username=?",username);
if(userList!=null&&userList.size()>=1){
return userList.get(0);
}
return null;
}
}
还有好多文件的代码没有贴出来,我实在不忍心再复制、粘贴下去了(浪费大家那么多时间),有兴趣的可以下载这个例子的源代码(由于这个例子牵涉的jar包比较大我就不把它们放进去了),我想以上这些文件的内容我就不用解释了,因为大家都学过SSH。本人初次整合它们,并没有使用这个整合方案做过项目,一定还有某些方面考虑的还不是太成熟,哪位大侠看了,还请多多批评指正,也希望谁有更好的整合方案,也共享一下,大家共同进步,共同提高!~^_^
相关推荐
在"Struts2+Spring2+Hibernate3整合方案"中,通常会将Struts2作为前端控制器,负责接收用户的HTTP请求并调用业务逻辑;Spring作为服务层,处理业务逻辑、进行事务管理和提供DAO(数据访问对象);Hibernate则在DAO层...
整合使用最新版本的三大框架(即Struts2、Spring4和Hibernate4),搭建项目架构原型。 项目架构原型:Struts2.3.16 + Spring4.1.1 + Hibernate4.3.6。 此外,还有:log4j、slf4j、junit4、ehcache等知识点。 项目...
轻量级JavaEE企业应用实战_Struts2+Spring3+Hibernate整合开发_第3版.part2
总的来说,"最新项目系统:Struts2+Spring4+Hibernate4三大框架整合"为学习和实践Java Web开发提供了一个实用的平台,对于提升开发者的技术水平和项目经验具有极大的帮助。通过深入研究和实践,开发者可以掌握Java ...
Struts 2+Spring 3+Hibernate框架技术精讲与整合案例Struts 2+Spring 3+Hibernate框架技术精讲与整合案例Struts 2+Spring 3+Hibernate框架技术精讲与整合案例Struts 2+Spring 3+Hibernate框架技术精讲与整合案例...
Struts2、Spring2.5和Hibernate3.2是Java Web开发中经典的三大框架,它们的整合使用在过去的许多年里被广泛应用于企业级应用系统。这个完整的项目提供了从开发环境到运行环境的所有必要组件,包括数据库脚本,使得...
轻量级JavaEE企业应用实战_Struts2+Spring3+Hibernate整合开发_第3版.part1
Struts 2+Spring 3+Hibernate框架技术精讲与整合案例3Struts 2+Spring 3+Hibernate框架技术精讲与整合案例3Struts 2+Spring 3+Hibernate框架技术精讲与整合案例3
Struts2+Spring+Hibernate和Struts2+Spring+Ibatis是两种常见的Java Web应用程序集成框架,它们分别基于ORM框架Hibernate和轻量级数据访问框架Ibatis。这两种框架结合Spring,旨在提供一个强大的、可扩展的、易于...
一个简单的spring+struts2+hibernate+mybatis整合(数据库脚本放在项目资源文件的sql目录下) 因为没想好mvc用springmvc好,还是struts2好 所以没有整合进去
《轻量级Java EE企业应用实战:Struts2+Spring3+Hibernate整合开发(第3版)》介绍了Java EE领域的三个开源框架:Struts 2、Spring和Hibernate。其中Struts 2升级到2.2.1,Spring升级到3.0.5,Hibernate升级到了...
Struts2、Spring和Hibernate是Java Web开发中的三大框架,它们的整合应用广泛用于构建复杂的Web应用程序,如本例中的图书馆管理系统。这个系统实现了用户登录和注册功能,并且提供了对书籍表的操作,包括增、删、改...
Java Web技术整合应用与项目实战 JSP+Servlet+Struts2+Hibernate+Spring3_13336769.zip.003 Java Web技术整合应用与项目实战 JSP+Servlet+Struts2+Hibernate+Spring3_13336769.zip.003
1. 配置环境:确保项目中引入了Struts2、Spring和Hibernate的相应库,这通常通过Maven或Gradle等构建工具完成。 2. 配置Spring:创建Spring的配置文件(如`applicationContext.xml`),定义Bean并设置其依赖。例如...