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 ...
随机推荐
- 高效开发技巧:为什么你下载Git项目这么慢?
文章首发于[博客园-陈树义],点击跳转到原文<高效开发技巧:为什么你下载Git项目这么慢?>. 笔者所在公司采用的是 GitLab 进行版本管理,但许多同事下载 Git 项目的路径是这样的 ...
- 合并 CentOS 6.8 的两个ISO镜像
合并 CentOS 6.8 的两个ISO镜像 1.创建相关目录: [root@local ~] mkdir -p /mnt/dvd1 /mnt/dvd2 /mnt/dvd3 /mnt/iso 说明: ...
- webp图像批量转换软件推荐——XnConvert
XnConvert是一款简单易用的批量图像格式转换软件,其所支持图片格式有JPG.PNG.TIFF.GIF.RAW.JPEG2000.WebP.OpenEXR等等.你可以轻松的实现图像格式的转换.缩放 ...
- Dora.Interception,为.NET Core度身打造的AOP框架:全新的版本
Dora.Interception 1.0(Github地址:可以访问GitHub地址:https://github.com/jiangjinnan/Dora)推出有一段时间了,最近花了点时间将它升级 ...
- 记一次python的一些参数
isdigit把字符串转化为整数 用法 if xx.isdigit(): xx=int(xx) index创建一个小原组,用法print(a.index(b),b)从0开始
- codechef [snackdown2017 Onsite Final] Minimax
传送门 题目描述 考虑一个 N 行 N 列的网格,行列编号均为 1 ∼ N.每个格子中包含一个整数.记 ri 为第 i 行的最小值,Ci 为第 i 列的最大值.我们称一个网格为好的,当且仅当满足:$$ ...
- Mybatis之基于XML的表之间映射
数据库表之间的关系有3种,一对一.一对多.多对多.既然是ORM,这肯定是必须有的.在学习EF的时候也有涉及,今天就是参考着EF的来学习下MyBatis的表关系映射. 一.准备工作 1.准备Model和 ...
- 百度分享到qq空间失败
QQ做了限制的,localhost是不会返回结果的,要用正式域名访问就可以了
- 网站搭建中,怎么区分ASP和PHP
1:空间支持上 ASP:程序要求比较低,空间只要支持ASP+access即可运行 PHP:配置要求比较高,空间需要支持PHP及数据库,而且程序和数据库是单独的,一般的 unix空间都是这种配置. 2: ...
- ftp上传文件,本地安装了,服务器上也需要在也安装一个ftp
服务器需要配置FTP服务: 你说的在你自己电脑上安装的只是一个FTP软件,用于连接远程服务器进行上传和下载文件的. 追问 在本地已经安装了,链接的话要在服务器上也安装一个吗? 追答 额,你有FTP服务 ...