整合Struts2+Hibernate5.0+Spring4.0
本整合采用struts利用文件配置
Hibernate用xml配置
Spring配置文件和注解
引入jar包
hibernate-release-5.2.7
struts-2.3.31
spring-framework-4.3.6
mysql 的数据驱动包
注意:引入log4j之后不要忘了去引入commons-logging-1.1.3.jar
配置文件
- struts2框架的配置文件
web.xml空文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置struts2.3版本的过滤器
<!-- struts2.3的配置文件 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
- Hibernate框架的配置文件
可以集成在Spring中。
- Spring框架的配置文件
web.xml中配置spring的监听器
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
applicationContext.xml 基本内容
<?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: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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
- log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.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=warn, stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
包的命名
工程目录struts2和spring的两种整合方式
- 1、Action的类由Struts2自身去创建
在struts.xml中配置
<package name="default" namespace="/" extends="struts-default">
<action name="product_*" class="com.ben.action.ProdouctAction" method="{1}">
</action>
</package>
applicationContext.xml中只配置service和dao
<!-- service层 -->
<bean id="productService" class="com.ben.service.impl.ProductServiceImpl">
<property name="productDAO">
<ref bean="productDAO"/>
</property>
</bean>
<!-- dao层 -->
<bean id="productDAO" class="com.ben.dao.impl.ProductDAOImpl"></bean>
- 2、Action的类交给Spring框架去创建
struts.xml改为
<package name="default" namespace="/" extends="struts-default">
<action name="product_*" class="productAction" method="{1}">
</action>
</package>
applicationContext.xml改为
<!-- action自动注入 -->
<bean id="productAction" class="com.ben.action.ProdouctAction" scope="prototype">
<property name="productService">
<ref bean="productService"/>
</property>
</bean>
hibernate与spring整合
- 创建pojo的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ben.pojo.Product" catalog="product">
<id name="pid" column="pid" type="java.lang.Integer">
<generator class="native"></generator>
</id>
<property name="pname" type="java.lang.String">
<column name="pname"></column>
</property>
<property name="price" type="java.lang.Double">
<column name="price"></column>
</property>
</class>
</hibernate-mapping>
- 在applicationContext.xml中配置数据库
<!-- 引入外部资源文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>${jdbc.driverClass}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<!-- 设置Hibernate相关内容 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/ben/pojo/Product.hbm.xml</value>
</list>
</property>
</bean>
- jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sshdemo
jdbc.username=root
jdbc.password=123456
- dao层做适当的修改
<!-- dao层 -->
<bean id="productDAO" class="com.ben.dao.impl.ProductDAOImpl">
<!-- 注入sessionFactory -->
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
- 事务配置
<!-- 事务管理 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
最终文件
pojo层文件
Product.java
package com.ben.pojo;
/**
* 产品的实体类
* @author zzq
*
*/
public class Product {
private Integer pid;
private String pname;
private Double price;
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Product() {
super();
}
public Product(Integer pid, String pname, Double price) {
super();
this.pid = pid;
this.pname = pname;
this.price = price;
}
@Override
public String toString() {
return "Product [pid=" + pid + ", pname=" + pname + ", price=" + price + "]";
}
}
Product.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ben.pojo.Product" catalog="sshdemo">
<id name="pid" column="pid" type="java.lang.Integer">
<generator class="native"></generator>
</id>
<property name="pname" type="java.lang.String" lazy="true">
<column name="pname"></column>
</property>
<property name="price" type="java.lang.Double" lazy="true">
<column name="price"></column>
</property>
</class>
</hibernate-mapping>
service层文件
ProductServiceImpl.java
package com.ben.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.ben.dao.IProductDAO;
import com.ben.pojo.Product;
import com.ben.service.IProdoctService;
@Service("productService")
public class ProductServiceImpl implements IProdoctService {
private IProductDAO productDAO;
@Override
public void save(Product product) {
System.out.println("ProductServiceImpl");
productDAO.save(product);
}
public IProductDAO getProductDAO() {
return productDAO;
}
@Resource(name="productDAO")
public void setProductDAO(IProductDAO productDAO) {
this.productDAO = productDAO;
}
}
dao层文件
package com.ben.dao.impl;
import javax.annotation.Resource;
import org.hibernate.FlushMode;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import com.ben.dao.IProductDAO;
import com.ben.pojo.Product;
@Repository("productDAO")
public class ProductDAOImpl extends HibernateDaoSupport implements IProductDAO{
@Override
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,timeout=10000,isolation=Isolation.DEFAULT)
public void save(Product product) {
System.out.println(product);
System.out.println("ProductDAOImpl");
getHibernateTemplate().save(product);
}
@Resource(name="sessionFactory")
public void setSessionFactory0(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
}
applicationContext.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task"
xmlns:p="http://www.springframework.org/schema/p" xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:jms="http://www.springframework.org/schema/jms" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.3.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 添加spring的注解扫描配置 -->
<context:component-scan base-package="com.ben"></context:component-scan>
<!-- 引入外部资源文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>${jdbc.driverClass}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<!-- 设置Hibernate相关内容 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.connection.autocommit">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/ben/pojo/Product.hbm.xml</value>
</list>
</property>
</bean>
<!-- 事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy"/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- struts2.3的配置文件 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
注意
1、在发现无法注入sessionFactory的时候,记得在dao层添加
@Resource(name="sessionFactory")
public void setSessionFactory0(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
2、在出现事务不能为“readonly”的时候,如果用的是hibernate3。可以在web.xml中添加解决问题,但是在hibernate5的配置中没有效果,点击源码发现,flushMode这个变量已经不见了,在方法中的调用中也显示已经过时
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
3、要用事务的配置,在applicationContext.xml 中配置(注解版)
在applicationContext.xml中添加
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy"/>
dao层中的方法上添加
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,timeout=10000,isolation=Isolation.DEFAULT)
4、事务配置,非注解版
<!-- 定义事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 下面使用aop切面的方式来实现 -->
<tx:advice id="TestAdvice" transaction-manager="transactionManager">
<!--配置事务传播性,隔离级别以及超时回滚等问题 -->
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<aop:config>
<!--配置事务切点 -->
<aop:pointcut id="services"
expression="execution(* com.ben.dao.impl.*.*(..))" />
<aop:advisor pointcut-ref="services" advice-ref="TestAdvice" />
</aop:config>
网友评论