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 ...
随机推荐
- (4程序框架)从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练
从零开始的嵌入式图像图像处理(PI+QT+OpenCV)实战演练 1综述http://www.cnblogs.com/jsxyhelu/p/7907241.html2环境架设http://www.cn ...
- sort()没有返回值
aList = [1,3,5,2,4] aList = aList.sort() print(aList) None
- JAVA基础-IO流(一)
一.IO流 IO流是Java为方便我们对文件的读写进行操作而提供的一种技术.按照读取写入文件的方式不同可以分为字符流和字节流,而每个流派按照功能又分为读和写.字符流读写操作的根类为Reader和Wri ...
- VirtualBox - RTR3InitEx failed with rc=-1912 (rc=-1912)
有一天重启电脑后虚拟机virtual box突然打不开了,提示类似 https://askubuntu.com/questions/900794/virtualbox-rtr3initex-faile ...
- ------- 当前全球最新的 IPv4 地址池使用报告 -------
-------------------------------------------------------------- 对于互联网行业相关的从业人员而言,时刻关注 IPv4 地址池的状态此类&q ...
- 385cc412a70eb9c6578a82ac58fce14c 教大家破解md5验证值
Md5密文破解(解密)可以说是网络攻击中的一个必不可少的环节,是工具中的一个重要"辅助工具".md5解密主要用于网络攻击,在对网站等进行入侵过程,有可能获得管理员或者其他用户的账号 ...
- MATLAB命令大全+注释小结
一.常用对象操作:除了一般windows窗口的常用功能键外.1.!dir 可以查看当前工作目录的文件. !dir& 可以在dos状态下查看.2.who 可以查看当前工作空间变量名, ...
- 洛谷 2634&&BZOJ 2152: 聪聪可可【点分治学习+超详细注释】
2152: 聪聪可可 Time Limit: 3 Sec Memory Limit: 259 MBSubmit: 3435 Solved: 1776[Submit][Status][Discuss ...
- HDU--1164
Eddy's research I Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- vuex的使用及持久化state的方式
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 当我们接触vuex的时候,这是我们最先看到 ...