详解Spring MVC事务配置
要了解事务配置的所有方法,请看一下《spring事务配置的5种方法》
本文介绍两种配置方法:
一、xml,使用tx标签配置拦截器实现事务
二、annotation方式
以下所使用环境为spring4.0.3、hibernate4.3.5
一、 xml,使用tx标签配置拦截器实现事务
entity类user.java,持久化类,对应数据库表user
package com.lei.demo.entity; import javax.persistence.*; @entity(name="users") public class users { public users(){ super(); } @id @generatedvalue(strategy=generationtype.auto) @column(name="id") private integer id; @column(name="user_name",length=32) private string user_name; @column(name="age") private integer age; @column(name="nice_name",length=32) private string nice_name; //属性实现...... }
userdao.javar,表user的一些操作,其中属性sessionfactory应该由spring注入,如下:
package com.lei.demo.dao; import java.util.list; import javax.annotation.resource; import org.hibernate.query; import org.hibernate.session; import org.hibernate.sessionfactory; import org.springframework.stereotype.repository; import com.lei.demo.entity.users; public class usersdao { private sessionfactory sessionfactory; public void setsessionfactory(sessionfactory sessionfactory) { this.sessionfactory = sessionfactory; } public sessionfactory getsessionfactory() { return sessionfactory; } public list<users> getalluser(){ string hsql="from users"; session session = sessionfactory.getcurrentsession(); query query = session.createquery(hsql); return query.list(); } }
userservice.java,业务实现类,如下
package com.lei.demo.service; import javax.annotation.resource; import org.springframework.stereotype.service; import org.springframework.transaction.annotation.isolation; import org.springframework.transaction.annotation.propagation; import org.springframework.transaction.annotation.transactional; import com.lei.demo.dao.*; public class userservice { private usersdao userdao; public int usercount(){ return userdao.getalluser().size(); } public usersdao getuserdao() { return userdao; } public void setuserdao(usersdao userdao) { this.userdao = userdao; } }
首先看一下xml配置,spring-hibernate.xml如下:
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <!-- hibernate4 --> <!-- 加载资源文件 其中包含变量信息,必须在spring配置文件的最前面加载,即第一个加载--> <context:property-placeholder location="classpath:persistence-mysql.properties" /> <bean id="sessionfactory" class="org.springframework.orm.hibernate4.localsessionfactorybean"> <property name="datasource" ref="datasource" /> <property name="packagestoscan"> <list> <!-- 可以加多个包 --> <value>com.lei.demo.entity</value> </list> </property> <property name="hibernateproperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!-- <prop key="hibernate.current_session_context_class">thread</prop> --> </props> </property> </bean> <!-- 数据库映射 --> <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="${jdbc.driverclassname}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.pass}" /> </bean> <!-- 配置hibernate事务管理器 --> <bean id="transactionmanager" class="org.springframework.orm.hibernate4.hibernatetransactionmanager"> <property name="sessionfactory" ref="sessionfactory" /> </bean> <!-- 配置事务异常封装 --> <bean id="persistenceexceptiontranslationpostprocessor" class="org.springframework.dao.annotation.persistenceexceptiontranslationpostprocessor" /> <!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionmanager --> <tx:advice id="txadvice" transaction-manager="transactionmanager"> <tx:attributes> <tx:method name="add*" propagation="required" /> <tx:method name="get*" propagation="required" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config expose-proxy="true"> <!-- 只对业务逻辑层实施事务 --> <aop:pointcut id="txpointcut" expression="execution(* com.lei.demo.service..*.*(..))" /> <!-- advisor定义,切入点和通知分别为txpointcut、txadvice --> <aop:advisor pointcut-ref="txpointcut" advice-ref="txadvice"/> </aop:config> </beans>
其中主要配置中是tx:advice和aop:config两个配置节,以spring aop的方式实现事务管理。
tx:advice配置了事务的管理者是transactionmanager,同时tx:method也规定了如果方法名匹配“add*”和“get*”方法时使用事务,propagation是设定事务的传播级别。除了“add*”和“get*”方法,其他的方法的事务是只读的(典型地,对于只执行查询的事务你会将该属性设为true,如果出现了更新、插入或是删除语句时只读事务就会失败)
aop:config指定了一个aop:pointcut去引用上边的advice。
这样就通过aop的拦截机制实现了事务,当然你还要用spring的方式自己配置userdao和userservice。
二、annotation方式
第一步,首先看一下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" xmlns:web="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"> <display-name>archetype created web application</display-name> <context-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <servlet> <servlet-name>lei-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>contextconfiglocation</param-name> <param-value>classpath:/lei-dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>lei-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
第二步,spring-hibernate配置,见以下spring-hibernate.xml配置
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <!-- hibernate4 --> <!-- 加载资源文件 其中包含变量信息,必须在spring配置文件的最前面加载,即第一个加载--> <context:property-placeholder location="classpath:persistence-mysql.properties" /> <bean id="sessionfactory" class="org.springframework.orm.hibernate4.localsessionfactorybean"> <property name="datasource" ref="datasource" /> <property name="packagestoscan"> <list> <!-- 可以加多个包 --> <value>com.lei.demo.entity</value> </list> </property> <property name="hibernateproperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!-- <prop key="hibernate.current_session_context_class">thread</prop> --> </props> </property> </bean> <!-- 数据库映射 --> <!-- class="org.apache.tomcat.dbcp.dbcp.basicdatasource" --> <!-- class="org.springframework.jdbc.datasource.drivermanagerdatasource" --> <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="${jdbc.driverclassname}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.pass}" /> </bean> <!-- 配置hibernate事务管理器 --> <bean id="transactionmanager" class="org.springframework.orm.hibernate4.hibernatetransactionmanager"> <property name="sessionfactory" ref="sessionfactory" /> </bean> <!-- 配置事务异常封装 --> <bean id="persistenceexceptiontranslationpostprocessor" class="org.springframework.dao.annotation.persistenceexceptiontranslationpostprocessor" /> </beans>
第一节中xml配置事务中需要通过配置tx:advice和aop:config来增加事务的功能。此处采用全注释方法,这两个配置节就不需要了。
相应的需要在视图解析配置中启用注释,如下lei-dispatcher-servlet.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <!-- 启动自动扫描 该包下所有的bean(@controller) --> <context:component-scan base-package="com.lei.demo" /> <!-- 基于注释的事务,当注释中发现@transactional时,使用id为“transactionmanager”的事务管理器 --> <!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 --> <tx:annotation-driven transaction-manager="transactionmanager"/> <!-- 定义视图解析器 --> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix"> <value>/web-inf/user/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
userdao如下
package com.lei.demo.dao; import java.util.list; import javax.annotation.resource; import org.hibernate.query; import org.hibernate.session; import org.hibernate.sessionfactory; import org.springframework.stereotype.repository; import com.lei.demo.entity.users; @repository public class usersdao { @resource(name="sessionfactory") private sessionfactory sessionfactory; public void setsessionfactory(sessionfactory sessionfactory) { this.sessionfactory = sessionfactory; } public sessionfactory getsessionfactory() { return sessionfactory; } public list<users> getalluser(){ string hsql="from users"; session session = sessionfactory.getcurrentsession(); query query = session.createquery(hsql); return query.list(); } }
userservice.java如下
package com.lei.demo.service; import javax.annotation.resource; import org.springframework.stereotype.service; import org.springframework.transaction.annotation.isolation; import org.springframework.transaction.annotation.propagation; import org.springframework.transaction.annotation.transactional; import com.lei.demo.dao.*; @service("userservice") public class userservice { @resource private usersdao userdao; @transactional public int usercount(){ return userdao.getalluser().size(); } public usersdao getuserdao() { return userdao; } public void setuserdao(usersdao userdao) { this.userdao = userdao; } }
这里,方法名usercount上加入@transactional,说明这个方法要启用事务。如果类名userservice上加入@transactional,则表明这个类中的所有方法都会启用事务。
如果配有多个transactionmanager,例如配置有transactionmanager1,和transactionmanager2,则可以通过@transactional(“transactionmanager1”),的方式指定使用哪个数据源的事务。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。