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 ...
随机推荐
- 解决api 跨域 webconfig添加节点
<system.webServer><httpProtocol><customHeaders><add name="Access-Control-A ...
- [转]Python 资源大全中文版
摘自:https://github.com/jobbole/awesome-python-cn 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列的资源整理.awesom ...
- [整]swp文件的处理
报错 vim非正常关闭,再下次编辑打开文件时均为显示如下警告信息: Swap file "test.xml.swp" already exists! [O]pen Read-Onl ...
- ajax解决跨域问题
1.在介绍之前先介绍几个概念 json: { date: "Sun Dec 24 21:44:42 CST 2017", temperature: "21", ...
- 读书笔记-JavaScript面向对象编程(三)
第7章 浏览器环境 7.1 在HTML页面中引入JavaScript代码 7.2概述BOM与DOM(页面以外事物对象和当前页面对象) 7.3 BOM 7.3.1 window对象再探(所以JavaSc ...
- Mybatis之基于XML的增删改查
这里先吐槽下,写的半天的东西,IE浏览器弹出调试窗口导致写的东西全部没保存,搞得我还要重新用谷歌写,思路全没了,fuck. 前面学习了下spring的DAO层,说起DAO层,那ORM肯定是少不了的,O ...
- [51nod][cf468D]1558 树中的配对
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1558 不是很懂dalao们用线段树是怎么写的…… 反正找出重心以后每个子 ...
- UVA 1584 字符串
VJ 该题 链接 https://vjudge.net/problem/UVA-1584 AC代码 字典序最小输出 #include <stdio.h> #include <m ...
- 最短路(spfa)
http://acm.hdu.edu.cn/showproblem.php?pid=2544 最短路 Time Limit: 5000/1000 MS (Java/Others) Memory ...
- c语言基础学习09_关于复合类型的复习
=============================================================================struct A{ char array[10 ...