Struts2.3.34+Hibernate 4.x+Spring4.x 整合二部曲之上部曲
1 导入jar包
- 可以复制jar包或maven导入,本文最后会给出github地址
2 导入log4j.properties文件
og4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
3 jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssh jdbc.user=root jdbc.password=root
4 因为是否需要hibernate.cfg.xml文件,所以Spring和Hibernate整合的方式有两种
4.1 Spring和Hibernate整合的方式一(需要hibernate.cfg.xml文件)
- 新建domain包,并在doamin包下新建pojo和对应的映射文件
- Classes.java
package com.xuweiwei.domain;
import java.io.Serializable;
//班级
public class Classes implements Serializable {
private Integer cid;
private String name;
private String description;
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
- Classes.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!--
class元素代表持久化类
name属性为类的全名
table 表名 默认值:类名
catalog 数据库的名字
-->
<class name="com.xuweiwei.domain.Classes">
<id name="cid" length="5">
<generator class="native"></generator>
</id>
<property name="name" length="20"></property>
<property name="description" length="50"></property>
</class>
</hibernate-mapping>
- 在src下新建hibernate.cfg.xml文件,并将Classes.hbm.xml文件导入,内容如下
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 一个sessionFactory代表数据库的一个连接 -->
<session-factory>
<!--
方言
告诉hibernate用什么样的数据库
-->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!--
validate 加载hibernate时,验证数据库的结构 默认值
update 加载hibernate时,检查数据库,如果表不存在,则创建,如果存在,则更新
create 每次加载hiberante,都会创建表
create-drop 每次加载hiberante,创建,卸载hiberante时,销毁
-->
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="com/xuweiwei/domain/Classes.hbm.xml"/>
</session-factory>
</hibernate-configuration>
- 在src下新建applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress InjectionValueTypeInspection -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="com.xuweiwei"/>
<!--
配置加载jdbc.properties的类
-->
<context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder>
<!--
配置c3p0连接池
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocations">
<list>
<value>classpath*:hibernate.cfg.xml</value>
</list>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启Spring的编程式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
- 【说明】:
- 如果你看过本人的Spring jdbc Template,地址:http://www.cnblogs.com/xuweiweiwoaini/p/8037903.html ,你就会知道其实Spring和Hibernate整合其实和Spring整合jdbc Template是一个套路。
- 比如我们需要HibernateDaoSupport这个父类,那么HibernateDaoSupport这个父类需要Spring注入SessionFactory对应,这个时候,你可能会想拿直接用SessionFactoryImpl,但是如果你去翻SessionFactoryImpl的源代码,你会发现以下几点:
- ①我们知道Hibernate是对JDBC的封装,那么你总需要注入DataSource数据源吧,很可惜,SessionFactory并没有提供setter方法或构造方法让我们将数据源DataSource注入,所以,这条路是行不通的。
- ②既然我们知道SessionFactoryImpl是行不通的,那么在Spring总需要拿到Session吧,怎么办?Spring提供了LocalSessionFactoryBean这个类,这个类可以让我们注入DataSource。

- 学过Hibernate知道,我们需要将hibernate.cfg.xml文件加载让Hibernate读取,那么我们需要在LocalSessionFactoryBean中配置一下,将hibernate.cfg.xml文件加载进去。

- 所以,我们可以通过configLocations或configLocation将hibernate.cfg.xml文件加载进去。
- 我们知道的是如果Spring整合jdbc Template对使用的事务管理器是DataSourceTransactionManager,那么Spring整合Hibernate使用的事务管理器是HibernateTransactionManager,其实在http://www.cnblogs.com/xuweiweiwoaini/p/8037903.html 中我已经说明了。

- 新建dao包,在dao包中新建ClassesDao.java和ClassesDaoImpl.java
- ClassesDao.java
package com.xuweiwei.dao;
import com.xuweiwei.domain.Classes;
public interface ClassesDao {
public static final String DAO_NAME= "com.xuweiwei.dao.impl.ClassesDaoImpl";
public void saveClasses(Classes classes);
}
- ClassesDaoImpl.java
package com.xuweiwei.dao.impl;
import com.xuweiwei.dao.ClassesDao;
import com.xuweiwei.domain.Classes;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
@Repository(ClassesDao.DAO_NAME)
public class ClassesDaoImpl extends HibernateDaoSupport implements ClassesDao {
@Resource(name="sessionFactory")
public void setSessionFactoryDI(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
@Override
public void saveClasses(Classes classes) {
this.getHibernateTemplate().save(classes);
}
}
- 新建service包,并在此包下新建ClassesService.java和ClassesServiceImpl.java
- ClassesService.java
package com.xuweiwei.service;
import com.xuweiwei.domain.Classes;
public interface ClassesService {
public static final String SERVICE_NAME = "com.xuweiwei.service.impl.ClassesServiceImpl";
public void saveClasses(Classes classes);
}
- ClassesServiceImpl.java
package com.xuweiwei.service.impl;
import com.xuweiwei.dao.ClassesDao;
import com.xuweiwei.domain.Classes;
import com.xuweiwei.service.ClassesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service(ClassesService.SERVICE_NAME)
@Transactional
public class ClassesServiceImpl implements ClassesService {
@Resource(name = ClassesDao.DAO_NAME)
private ClassesDao classesDao ;
@Override
public void saveClasses(Classes classes) {
classesDao.saveClasses(classes);
}
}
- 新建test包,并新建TestHibernate.java
package com.test;
import com.xuweiwei.domain.Classes;
import com.xuweiwei.service.ClassesService;
import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestHibernate {
@Resource(name="sessionFactory")
private SessionFactory sessionFactory;
@Resource(name = ClassesService.SERVICE_NAME)
private ClassesService classesService;
@Test
public void testSessionFactory(){
System.out.println(sessionFactory);
}
@Test
public void save(){
Classes classes = new Classes();
classes.setName("许威威");
classes.setDescription("java开发");
System.out.println(classesService);
classesService.saveClasses(classes);
}
}

4.2 Spring和Hibernate整合的方式二(不需要hibernate.cfg.xml文件)
- 我们知道hibernate.cfg.xml文件除了可以配置一些方言等属性,还可以加载映射文件,如果Spring可以自动加载那些映射文件,并设置方言属性,那么是不是意味着hibernate.cfg.xml没有用了。
- 还有,我们知道Spring在进行注解开发的时候,设置了一个扫描器,那么我们是否可以联系,只要给定固定的路径,Spring再提供一个扫描器去扫描给定路径下的所有映射文件,这样是不是hibernate.cfg.xml文件的作用完全没有了。
- 所以,不需要配置hibernate.cfg.xml文件的情况下,applicationContext.xml文件的配置信息如下:
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress InjectionValueTypeInspection -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<context:component-scan base-package="com.xuweiwei"/>
<!--
配置加载jdbc.properties的类
-->
<context:property-placeholder location="classpath*:jdbc.properties"></context:property-placeholder>
<!--
配置c3p0连接池
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingDirectoryLocations">
<!--
mappingDirectoryLocations:可以扫描domain包下的所有映射文件
-->
<list>
<value>classpath*:com/xuweiwei/domain</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hbm2ddl.auto">update</prop>
<prop key="show_sql">true</prop>
<prop key="format_sql">true</prop>
</props>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 开启Spring的编程式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
- 其他步骤和4.1相同

5 项目地址
Struts2.3.34+Hibernate 4.x+Spring4.x 整合二部曲之上部曲的更多相关文章
- Struts2.3.34+Hibernate 4.x+Spring4.x 整合二部曲之下部曲
1 导入jar包 本文最后会给出项目的地址,各位无须看急. 2 配置web.xml文件 <?xml version="1.0" encoding="UTF-8&qu ...
- Struts2,Spring, Hibernate三大框架SSH的整合步骤
整合步骤 创建web工程 引入相应的jar包 整合spring和hibernate框架 编写实体类pojo和hbm.xml文件 编写bean-base.xml文件 <!-- 1) 连接池实例 - ...
- Struts2+Hibernate4+Spring4框架整合搭建Java项目原型
收藏 http://www.cnblogs.com/mageguoshi/p/5850956.html Struts2+Hibernate4+Spring4框架整合搭建Java项目原型
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合(转载)
孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(八)--Mybatis3.x与Spring4.x整合 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: m ...
- Struts 2.x 与Spring4.x整合出现:No mapping found for dependency [type=java.lang.String, name='actionPackages...
Struts2.16与Spring4.x整合出错: Caused by: java.lang.RuntimeException: com.opensymphony.xwork2.inject.Depe ...
- 项目ITP(六) spring4.0 整合 Quartz 实现动态任务调度
前言 系列文章:[传送门] 项目需求: http://www.cnblogs.com/Alandre/p/3733249.html 上一博客写的是基本调度,后来这只能用于,像每天定个时间 进行数据库备 ...
- 项目ITP(五) spring4.0 整合 Quartz 实现任务调度
前言 系列文章:[传送门] 项目需求: 二维码推送到一体机上,给学生签到扫描用.然后需要的是 上课前20分钟 ,幸好在帮带我的学长做 p2p 的时候,接触过.自然 quartz 是首选.所以我就配置了 ...
- [CXF REST标准实战系列] 二、Spring4.0 整合 CXF3.0,实现测试接口(转)
转自:[CXF REST标准实战系列] 二.Spring4.0 整合 CXF3.0,实现测试接口 文章Points: 1.介绍RESTful架构风格 2.Spring配置CXF 3.三层初设计,实现W ...
- Hibernate注解使用以及Spring整合
Hibernate注解使用以及Spring整合 原文转自:http://wanqiufeng.blog.51cto.com/409430/484739 (1) 简介: 在过去几年里,Hibernate ...
随机推荐
- MyEclipse2015上传项目到GitHub(很详细)
MyEclipse 2015 默认已经安装了git插件,在MyEclipse中上传项目到github的步骤如下: 1.github官网(https://github.com)申请开通账号(略) 1.1 ...
- [转载自阿里丁奇]各版本MySQL并行复制的实现及优缺点
MySQL并行复制已经是老生常谈,笔者从2010年开始就着手处理线上这个问题,刚开始两三年也乐此不疲分享,现在再提这个话题本来是难免"炒冷饭"嫌疑. 最近触发再谈这个话题,是 ...
- win10 uwp 横向 AppBarButton
一般看到的 AppBarButton 都是图片在上面,文字在下面,是否可以更改让文字在和图片相同的位置?本文告诉大家如何做出横向的 AppBarButton 把图标和文本放在一起. 如果需要添加 Ap ...
- Erlang/OTP设计原则(文档翻译)
http://erlang.org/doc/design_principles/des_princ.html 图和代码皆源自以上链接中Erlang官方文档,翻译时的版本为20.1. 这个设计原则,其实 ...
- 详说 Navicat for MySQL 快捷键
详说 Navicat for MySQL 快捷键: Navicat 主窗口 Navicat 主窗口快捷键 常规 Navicat 常规快捷键 表设计器 Navicat 表设计器快捷键 表查看器 Navi ...
- 微信小程序登陆授权
小程序前端代码 function WXlogin(){ wx.login({ success: function (code) { wx.getUserInfo({ success:function( ...
- [翻译].NET Shell Extensions - Shell Context Menus---.net 外壳扩展-右键菜单
我自己的前言说明: 本文原作者为 Dave Kerr,原文链接为.NET Shell Extensions - Shell Context Menus:,我是在为了完成最新需求的时候查询资料的时 ...
- BZOJ 1088: [SCOI2005]扫雷Mine【思维题,神奇的模拟+枚举】
1088: [SCOI2005]扫雷Mine Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 3791 Solved: 2234[Submit][St ...
- HDU 2147 kiki's game(规律,博弈)
kiki's game Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 40000/10000 K (Java/Others)Total ...
- 将id传过去,根据id显示下面的详情页面
官方demo:http://dev.dcloud.net.cn/mui/event/ 假设如下场景:从新闻列表页面进入新闻详情页面,新闻详情页面为共用页面,通过传递新闻ID通知详情页面需要显示具体哪个 ...