现在spring3.2能整合spring hibernate整合4.2吗

Hibernate4.2和Spring3.2的整合问题
spring3.1以后的版本去掉了HibernateDaoSupport这个工具,也就不存在getTemplate()方法了。
我的疑问是:1.spring关于“sessionFactory”的一系列bean的配置(包括连接池)不是无法使用注入的方式
来支持dao实例了吗?
2.若使用spring3.2和hibernate4.2整合,事务管理应该给哪一方比较好?
&?xml version=&1.0& encoding=&UTF-8&?&
&beans xmlns=&http://www.springframework.org/schema/beans&
xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xmlns:aop=&http://www.springframework.org/schema/aop&
xmlns:context=&http://www.springframework.org/schema/context&
xmlns:tx=&http://www.springframework.org/schema/tx&
xsi:schemaLocation=&http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd &&
&bean id=&dataSource& class=&com.mchange.boPooledDataSource& destroy-method=&close&&
&property name=&driverClass& value=&com.mysql.jdbc.Driver&/&
&property name=&jdbcUrl& value=&jdbc:mysql://localhost:3306/mycms?useUnicode=true&characterEncoding=UTF-8&/&
&property name=&user& value=&root&/&
&property name=&password& value=&123456&/&
&property name=&maxPoolSize& value=&100&/&
&property name=&minPoolSize& value=&3&/&
&property name=&initialPoolSize& value=&3&/&
&property name=&maxIdleTime& value=&120&/&
&bean id=&sessionFactory&
class=&org.springframework.orm.hibernate4.LocalSessionFactoryBean&&
&property name=&dataSource& ref=&dataSource&/&
&property name=&hibernateProperties&&
&prop key=&hibernate.dialect&&org.hibernate.dialect.MySQL5Dialect&/prop&
&prop key=&hibernate.generate_statistics&&true&/prop&
&prop key=&hibernate.hbm2ddl.auto&&update&/prop&
&prop key=&hibernate.cglib.use_reflection_optimizer&&true&/prop&
&prop key=&hibernate.current_session_context_class&&org.springframework.orm.hibernate4.SpringSessionContext&/prop&
&prop key=&hibernate.cache.provider_configuration_file_resource_path&&classpath:ehcache.xml&/prop&
&prop key=&hibernate.cache.region.factory_class&&org.hibernate.cache.ehcache.EhCacheRegionFactory&/prop&
&prop key=&hibernate.cache.use_query_cache&&true&/prop&
&prop key=&hibernate.cache.use_second_level_cache&&true&/prop&
&prop key=&hibernate.generate_statistics&&true&/prop&
&prop key=&hibernate.max_fetch_depth&&2&/prop&
&prop key=&hibernate.order_updates&&true&/prop&
&prop key=&hibernate.connection.autocommit&&false&/prop&
&prop key=&hibernate.show_sql&&true&/prop&
&prop key=&format_sql&&true&/prop&
&/property&
&property name=&packagesToScan& value=&com.codeworker.mycms&/&
&context:component-scan base-package=&com.codeworker.mycms&&
&context:include-filter type=®ex& expression=&..*ServiceImpl&/&
&/context:component-scan&
&context:component-scan base-package=&com.codeworker.mycms&&
&context:include-filter type=®ex& expression=&..*DaoImpl&/&
&/context:component-scan&
&aop:aspectj-autoproxy/&
&!-- 声明使用注解式事务 --&
&tx:annotation-driven transaction-manager=&transactionManager&/&
&bean id=&transactionManager&
class=&org.springframework.orm.hibernate4.HibernateTransactionManager&&
&property name=&sessionFactory& ref=&sessionFactory&/&
&!-- 将Hibernate异常转变成Spring的DataAccessException异常,保持一致的异常处理方式 --&
&bean class=&org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor&/&
&bean id=&jdbcTemplate& class=&org.springframework.jdbc.core.JdbcTemplate&&
&property name=&dataSource& ref=&dataSource& /&
主要是以annotation实现事务处理,在Service层处理。
* Copyright (c) 2012 DongXiangli.All rights reserved.
package com.codeworker.utils.
import org.hibernate.C
import org.hibernate.Q
import org.hibernate.S
import org.hibernate.SessionF
import org.hibernate.criterion.*;
import org.hibernate.internal.CriteriaI
import org.hibernate.transform.ResultT
import org.slf4j.L
import org.slf4j.LoggerF
import org.springframework.util.A
import java.io.S
import java.util.ArrayL
import java.util.L
* User: DongXiangli
* Date: 12-12-24
* Time: 上午10:44
public class AbstractDao&T, PK extends Serializable& {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
protected Class&T& entityC
private SessionFactory sessionF
public AbstractDao(SessionFactory sessionFactory, Class&T& entityClass) {
this.sessionFactory = sessionF
this.entityClass = entityC
public Session getSession() {
return sessionFactory.getCurrentSession();
public SessionFactory getSessionFactory() {
return sessionF
public void save(T entity) {
Assert.notNull(entity);
getSession().saveOrUpdate(entity);
(&save entity: {}&, entity);
public void delete(T entity) {
Assert.notNull(entity);
getSession().delete(entity);
(&delete entity: {}&, entity);
public void delete(PK id) {
Assert.notNull(id);
getSession().delete(getSession().load(entityClass, id));
public int delete(PK[] ids) {
Assert.notNull(ids);
int i = 0;
for (PK id : ids) {
delete(id);
public List&T& findAll() {
return findByCriteria();
public PageUtils&T& findAll(PageUtils&T& page) {
return findByCriteria(page);
* 按id获取对象.
public T get(final PK id) {
Assert.notNull(id);
return (T) getSession().get(entityClass, id);
* 按HQL查询对象列表.
* @param hql
* @param values 数量可变的参数
public List&T& find(String hql, Object... values) {
return createQuery(hql, values).list();
* 按HQL分页查询.
* 暂不支持自动获取总结果数,需用户另行执行查询.
* @param page
分页参数.包括pageSize 和firstResult.
* @param hql
* @param values 数量可变的参数.
* @return 分页查询结果, 附带结果列表及所有查询时的参数.
public PageUtils&T& find(PageUtils&T& page, String hql, Object... values) {
Assert.notNull(page);
if (page.isAutoCount()) {
logger.warn(&HQL查询暂不支持自动获取总结果数,hql为{}&, hql);
Query q = createQuery(hql, values);
if (page.isFirstSetted()) {
q.setFirstResult(page.getFirst());
if (page.isPageSizeSetted()) {
q.setMaxResults(page.getPageSize());
page.setData(q.list());
//返回指定数量的查询结果
public List&T& findByCount(int iCount, String hql, Object... values) {
Query q = createQuery(hql, values);
q.setMaxResults(iCount);
return q.list();
* 按HQL查询唯一对象.
public Object findUnique(String hql, Object... values) {
return createQuery(hql, values).uniqueResult();
* 按HQL查询Intger类形结果.
public Integer findInt(String hql, Object... values) {
return ((Long) findUnique(hql, values)).intValue();
* 按HQL查询Long类型结果.
public Long findLong(String hql, Object... values) {
return (Long) findUnique(hql, values);
* 按Criterion查询对象列表.
* @param criterion 数量可变的Criterion.
public List&T& findByCriteria(Criterion... criterion) {
return createCriteria(criterion).list();
* 按Criterion分页查询.
* @param page
分页参数.包括pageSize、firstResult、orderBy、asc、autoCount.
其中firstResult可直接指定,也可以指定pageNo.
autoCount指定是否动态获取总结果数.
* @param criterion 数量可变的Criterion.
* @return 分页查询结果.附带结果列表及所有查询时的参数.
public PageUtils&T& findByCriteria(PageUtils&T& page, Criterion... criterion) {
Assert.notNull(page);
Criteria c = createCriteria(criterion);
c.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
if (page.isAutoCount()) {
page.setTotalCount(countQueryResult(page, c));
if (page.isFirstSetted()) {
c.setFirstResult(page.getFirst());
if (page.isPageSizeSetted()) {
c.setMaxResults(page.getPageSize());
if (page.isOrderBySetted()) {
if (page.getOrder().endsWith(PageUtils.ASC)) {
c.addOrder(Order.asc(page.getOrderBy()));
c.addOrder(Order.desc(page.getOrderBy()));
page.setData(c.list());
* 按属性查找对象列表.
public List&T& findByProperty(String propertyName, Object value) {
Assert.hasText(propertyName);
return createCriteria(Restrictions.eq(propertyName, value)).list();
* 按属性查找唯一对象.
public T findUniqueByProperty(String propertyName, Object value) {
Assert.hasText(propertyName);
return (T) createCriteria(Restrictions.eq(propertyName, value)).uniqueResult();
* 根据查询函数与参数列表创建Query对象,后续可进行更多处理,辅助函数.
public Query createQuery(String queryString, Object... values) {
Assert.hasText(queryString);
Query queryObject = getSession().createQuery(queryString);
if (values != null) {
for (int i = 0; i & values. i++) {
queryObject.setParameter(i, values[i]);
return queryO
* 根据Criterion条件创建Criteria,后续可进行更多处理,辅助函数.
public Criteria createCriteria(Criterion... criterions) {
Criteria criteria = getSession().createCriteria(entityClass);
for (Criterion c : criterions) {
criteria.add(c);
* 判断对象的属性值在数据库内是否唯一.
* 在修改对象的情景下,如果属性新修改的值(value)等于属性原值(orgValue)则不作比较.
* 传回orgValue的设计侧重于从页面上发出Ajax判断请求的场景.
* 否则需要SS2里那种以对象ID作为第3个参数的isUnique函数.
public boolean isPropertyUnique(String propertyName, Object newValue, Object orgValue) {
if (newValue == null || newValue.equals(orgValue))
Object object = findUniqueByProperty(propertyName, newValue);
return (object == null);
* 通过count查询获得本次查询所能获得的对象总数.
* @return page对象中的totalCount属性将赋值.
protected long countQueryResult(PageUtils&T& page, Criteria c) {
CriteriaImpl impl = (CriteriaImpl)
// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
Projection projection = impl.getProjection();
ResultTransformer transformer = impl.getResultTransformer();
List&CriteriaImpl.OrderEntry& orderEntries =
orderEntries = (List&CriteriaImpl.OrderEntry&) BeanUtils.getFieldValue(impl, &orderEntries&);
BeanUtils.setFieldValue(impl, &orderEntries&, new ArrayList&CriteriaImpl.OrderEntry&());
} catch (Exception e) {
logger.error(&不可能抛出的异常:{}&, e.getMessage());
// 执行Count查询
long totalCount = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
if (totalCount & 1)
return -1;
// 将之前的Projection和OrderBy条件重新设回去
c.setProjection(projection);
if (projection == null) {
c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
if (transformer != null) {
c.setResultTransformer(transformer);
BeanUtils.setFieldValue(impl, &orderEntries&, orderEntries);
} catch (Exception e) {
logger.error(&不可能抛出的异常:{}&, e.getMessage());
return totalC
这是经常用到的一个DAO模板类
这个其中用到的PageUtils。
* Copyright (c) 2012 DongXiangli.All rights reserved.
package com.codeworker.utils.
import java.io.S
import java.util.L
* User: DongXiangli
* Date: 12-12-23
* Time: 下午10:48
public class PageUtils&T& implements Serializable {
public static final String ASC = &asc&;
public static final String DESC = &desc&;
protected int pageNo = 1;
//当前页号
protected int pageSize = -1;
//页内记录数
protected String orderBy =
//排序字段,基本没有使用
protected String order = ASC;
//排序方向
protected boolean autoCount =
//自动计算记录数
private List&T& data =
private long totalCount = -1;
//总记录数
public PageUtils() {
this(1, 20);
public PageUtils(int pageIndex) {
this(pageIndex, 20);
public PageUtils(int pageIndex, int pageSize) {
if (pageIndex & 1) pageIndex = 1;
if (pageSize & 1) pageSize = 15;
this.pageNo = pageI
this.pageSize = pageS
public PageUtils(int pageSize, boolean autoCount) {
if (pageSize &= 0) {
pageSize = 20;
this.pageSize = pageS
this.autoCount = autoC
* 获得每页的记录数量,无默认值.
public int getPageSize() {
return pageS
public void setPageSize(int pageSize) {
this.pageSize = pageS
* 是否已设置每页的记录数量.
public boolean isPageSizeSetted() {
return pageSize & -1;
* 获得当前页的页号,序号从1开始,默认为1.
public int getPageNo() {
return pageNo;
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
* 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从0开始.
public int getFirst() {
if (pageNo & 1 || pageSize & 1)
return -1;
return ((pageNo - 1) * pageSize);
* 是否已设置第一条记录记录在总结果集中的位置.
public boolean isFirstSetted() {
return (pageNo & 0 && pageSize & 0);
* 获得排序字段,无默认值.
public String getOrderBy() {
return orderBy;
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
* 是否已设置排序字段.
public boolean isOrderBySetted() {
if (orderBy != null) {
orderBy = orderBy.trim();
return !orderBy.isEmpty();
* 获得排序方向,默认为asc.
public String getOrder() {
* 设置排序方式向.
* @param order 可选值为desc或asc.
public void setOrder(String order) {
if (ASC.equalsIgnoreCase(order) || DESC.equalsIgnoreCase(order)) {
this.order = order.toLowerCase();
throw new IllegalArgumentException(&order should be 'desc' or 'asc'&);
* 是否自动获取总页数,默认为false.
* 注意本属性仅于query by Criteria时有效,query by HQL时本属性无效.
public boolean isAutoCount() {
return autoC
public void setAutoCount(boolean autoCount) {
this.autoCount = autoC
* 取得倒转的排序方向
public String getInverseOrder() {
if (order.endsWith(DESC))
return ASC;
return DESC;
* 页内的数据列表.
public List&T& getData() {
return this.
public void setData(List&T& data) {
this.data =
* 总记录数.
public long getTotalCount() {
return totalC
public void setTotalCount(long totalCount) {
this.totalCount = totalC
* 计算总页数.
public long getTotalPages() {
if (totalCount == -1)
long count = totalCount / pageS
if (totalCount % pageSize & 0) {
* 是否还有下一页.
public boolean isHasNext() {
return (pageNo + 1 &= getTotalPages());
* 返回下页的页号,序号从1开始.
public int getNextPage() {
if (isHasNext())
return pageNo + 1;
return pageNo;
* 是否还有上一页.
public boolean isHasPre() {
return (pageNo - 1 &= 1);
* 返回上页的页号,序号从1开始.
public int getPrePage() {
if (isHasPre())
return pageNo - 1;
return pageNo;
有这个,基本上就可以实现DAO层了。
以下是我的版本信息:
&version.springframework&3.2.4.RELEASE&/version.springframework&
&version.aopalliance&1.0&/version.aopalliance&
&version.aspectj.aspectjweaver&1.6.11&/version.aspectj.aspectjweaver&
&version.springframework.security&3.1.4.RELEASE&/version.springframework.security&
&version.hibernate&4.2.5.Final&/version.hibernate&
&version.hibernate-validator&4.3.1.Final&/version.hibernate-validator&
&version.hibernate-jpa&1.0.1.Final&/version.hibernate-jpa&
额...自己再做一个demo试试~~
居然还有人自己写
实际上在spring3和hibernate4的结合中,直接注入sessionFactory就可以了,然后再配置一下OpenSessionInViewFilter就OK了。接下来的都是小问题了。
话说上面的兄弟竟然直接上代码,佩服佩服。
--- 共有 1 条评论 ---
我就忘记给他WEB。XML了。自己看着来吧。不会描述,只有直接上代码了。
引用来自“东向利”的*** 主要是以annotation实现事务处理,在Service层处理。
annotation我不知道好在哪里
独立开发者差不多
就是一个屁用没有的噱头而已
代码简直无法维护,无法阅读,无法跟踪等等等等等等
只有那些提着怪七八糟的需求的程序猿能想出这个东西来!一步一步整合Java&SSH&(Struts2.3.15.1+Hibernate4.2.3.f+Spring3.2.3.r)(一)
作者:m00nin &转载请注明出处
/otn-pub/java/jdk/7u25-b17/jdk-7u25-windows-i586.exe
http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/kepler/R/eclipse-jee-kepler-R-win32.zip
/apache-mirror/tomcat/tomcat-7/v7.0.42/bin/apache-tomcat-7.0.42-windows-x86.zip
/get/Downloads/MySQL-5.6/mysql-5.6.12-win32.zip/from//
http://mirrors./apache//struts/binaries/struts-2.3.15.1-all.zip
Hibernate4
http://sourceforge.net/projects/hibernate/files/hibernate4/4.2.3.Final/hibernate-release-4.2.3.Final.zip/download
http://repo.springsource.org/libs-release-local/org/springframework/spring/3.2.3.RELEASE/spring-framework-3.2.3.RELEASE-dist.zip
/get/Downloads/Connector-J/mysql-connector-java-5.1.25.zip/from//
http://www.slf4j.org/dist/slf4j-1.7.5.zip
http://www.apache.org/dyn/closer.cgi/logging/log4j/1.2.17/log4j-1.2.17.zip
http://www.eclipse.org/downloads/download.php?file=/tools/aspectj/aspectj-1.7.3.jar
http://sourceforge.net/projects/cglib/files/cglib2/2.2.3/cglib.2.2.3.zip/download
/apache//commons/dbcp/binaries/commons-dbcp-1.4-bin.zip
/apache-mirror//commons/pool/binaries/commons-pool-1.6-bin.zip
我的64位机器,***版本:JDK7,Eclipse(juno)、Tomcat(7.0.40)、Mysql(5.0.90)
SSH版本,如上表。
1、新建工程:
ALT="一步一步整合Java&SSH&(Struts2.3.15.1+Hibernate4.2.3.f+Spring3.2.3.r)(一)" />
2、引入SSH包:
ALT="一步一步整合Java&SSH&(Struts2.3.15.1+Hibernate4.2.3.f+Spring3.2.3.r)(一)" />
Hibernate:
ALT="一步一步整合Java&SSH&(Struts2.3.15.1+Hibernate4.2.3.f+Spring3.2.3.r)(一)" />
加入Spring下面所有包
ALT="一步一步整合Java&SSH&(Struts2.3.15.1+Hibernate4.2.3.f+Spring3.2.3.r)(一)" />
首先,放入一个index.html文件。
在eclipse中启动tomcat时出现Setting
property 'source' to
'org.eclipse.jst.jee.server:ProjectName'&&
did not find a matching property错误。
解决办法:(对于Tomcat7.0,告警依然存在,但不影响!)
1、在服务器上点右键--属性,general选项卡中点switch
location,这时,location变为:/servers/tomcatX.0
server at localhost.server。
ALT="一步一步整合Java&SSH&(Struts2.3.15.1+Hibernate4.2.3.f+Spring3.2.3.r)(一)" />
2、停止Tomcat服务,在project
explore中找到tomcat项目--Tomcat
vX.0 Server at localhost.server&
,双击打开,在最下面的server
option里选中publis
module context to separate xml files保存。重启Tomcat,完成,可以看到index.html。
ALT="一步一步整合Java&SSH&(Struts2.3.15.1+Hibernate4.2.3.f+Spring3.2.3.r)(一)" />
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

参考资料

 

随机推荐