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/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>spring-mvc</display-name>
<!--配置欢迎界面 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/exception.jsp</location>
</error-page>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Log4j配置 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</context-param>
<!-- 开一条watchdog线程每60秒扫描一下配置文件的变化 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<!--配置log4j包 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!--配置listener -->
<!--在这里可以配置spring的监听器,启动的时候需要把spring中的bean都注册到spring容器中 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置filter对编码进行转换 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value><!-- 强制转码 -->
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置servlet -->
<!--我们希望spring的控制器比其他servlet优先启动,所以你需要设置load-on-startup
这个东西:值越小越先启动(0-5),没有或者为负数的时候,servlet被选用的时候才加载-->
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:controll-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>sessionFactory</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
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:aop="http://www.springframework.org/schema/aop"
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:hibernate.properties</value>
</list>
</property>
</bean>
<!-- DWR配置-->
<dwr:annotation-config></dwr:annotation-config>
<!-- 扫描需要转换的java对象 -->
<dwr:annotation-scan scanRemoteProxy="true"
base-package="com.tb.service" />
<!-- 部署项目时, 请把debug设为false
<dwr:controller id="dwrController" debug="true" /> -->
<!--DWR初始化配置 -->
<dwr:configuration></dwr:configuration>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${db.driver}</value>
</property>
<property name="jdbcUrl">
<value>${db.url}</value>
</property>
<property name="user">
<value>${db.user}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
<property name="maxPoolSize">
<value>300</value>
</property>
<property name="minPoolSize">
<value>1</value>
</property>
<property name="initialPoolSize">
<value>1</value>
</property>
<property name="maxIdleTime">
<value>60</value>
</property>
<property name="acquireIncrement">
<value>5</value>
</property>
<property name="acquireRetryAttempts">
<value>10</value>
</property>
<property name="acquireRetryDelay">
<value>1000</value>
</property>
<property name="autoCommitOnClose">
<value>true</value>
</property>
<property name="breakAfterAcquireFailure">
<value>false</value>
</property>
<property name="checkoutTimeout">
<value>100</value>
</property>
<property name="idleConnectionTestPeriod">
<value>60</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 让spring帮你扫描这个包底下的所有类,主要作用扫描跟数据库对应的实体类 -->
<!-- 设置hibernate的属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.OracleDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_outer_join">true </prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true </prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.default_batch_fetch_size">16</prop>
<prop key="hibernate.c3p0.max_size">300</prop>
<prop key="hibernate.c3p0.min_size">1</prop>
<prop key="hibernate.c3p0.timeout">60</prop>
<prop key="hibernate.c3p0.max_statements">100</prop>
<prop key="hibernate.c3p0.idle_test_period">60</prop>
<prop key="hibernate.c3p0.acquire_increment">5</prop>
<prop key="hibernate.c3p0.validate">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
<property name="packagesToScan" value="com.tb.model"/>
</bean>
<!--事务配置 -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 开启AOP监听 只对当前配置文件有效 -->
<aop:aspectj-autoproxy expose-proxy="true" />
<!-- 开启注解事务 只对当前配置文件有效 -->
<tx:annotation-driven transaction-manager="txManager"/>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="merge*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="put*" propagation="REQUIRED" />
<tx:method name="execute*" propagation="REQUIRED" rollback-for ="Exception.class" />
<tx:method name="tes*" propagation="REQUIRED" />
<tx:method name="use*" propagation="REQUIRED" />
<!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 -->
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="count*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="list*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" rollback-for ="Exception.class"/>
</tx:attributes>
</tx:advice>
<bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true" lazy-init="true">
<property name="transactionManager" ref="txManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="tes*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="execute*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop>
<prop key="load*">PROPAGATION_REQUIRED, -Exception</prop>
</props>
</property>
</bean>
<!-- 只对业务逻辑层实施事务 -->
<aop:config expose-proxy="true">
<aop:pointcut id="txPointcut" expression="execution(* com.tb.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" />
</aop:config>
<!-- -->
<!--配置拦截器 在springmvc的控制器配置文件中,你就可以这么配置拦截器,具体你在拦截器里面做什么,自己去做
<mvc:interceptors>
多个拦截器,顺序执行
<mvc:interceptor>
这里的path符号有/*, /**, *, ? 等,对于student.do?param=1从?开始不作为path
如果不配置或/*,将拦截所有的Controller
<mvc:mapping path="/student/save*" />
<bean class="spring.common.interceptor.FromDupInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
-->
</beans>
controll-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">
<context:component-scan base-package="com.tb">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:component-scan base-package="com.tb"/>
<!-- json -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" valu-e=".jsp"/>
</bean>
</beans>
以上为配置文件:包路径分别为com.tb.action;com.tb.service;com.tb.model;com.tb.dao;
其中com.tb.service下面又分com.tb.service.impl;com.tb.dao包下又分com.tb.dao.impl;
但是现在测试事物一直控制不了,请大神帮忙原因。测试方法:
Controller.java
@RequestMapping(params = "executeSearch")
@Transactional
public String executeSearch(HttpServletRequest request) {
//测试事物控制。
infoService.test();
return "info/search";
}
ServiceImpl.java
public void test(){
try {
infoDAO.test();
} catch (Exception e) {
e.printStackTrace();
}
}
Service.java
@Transactional
public void test();
DaoImpl.java
@Transactional
public void test() {
try {
String sql = "update operation_log set username='1' where id='1'";
List<Object> condition = new ArrayList<Object>();
this.executeUpdateBySql(sql, condition);
String sql1 = "update operation_log set username=33, where id='1'";
this.executeUpdateBySql(sql1, condition);
} catch (RuntimeException e) {
e.printStackTrace();
}
}
DaoImpl.java继承HibernateDao
HibernateDao.java
/***************注入***********/
@Resource
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
//事务配置后,可通过getCurrentSession方法获得session
return sessionFactory.getCurrentSession();
}
public int executeUpdateBySql(final String sql,final List<Object> conditions){
try {
Query query = getSession().createSQLQuery(sql);
if(conditions!=null && conditions.size()>0){
for(int i=0;i<conditions.size();i++){
if(conditions.get(i)!=null && !conditions.get(i).equals("")){
query.setParameter(i, conditions.get(i));
}
}
}
return query.executeUpdate();
} catch (RuntimeException e) {
throw e;
}finally{
System.out.println(getSessionFactory().getCurrentSession().beginTransaction().isActive());
}
}
整体代码是这样的,在运行daoImpl.java中test()方法的时候执行第一条SQL时会提交事物,直接修改数据库中的值,执行第二条SQL时会报错,理论上应该都不提交事物。但实际上第一条执行了之后就提交事物了,不知道是我框架问题还是我写的问题,求大神帮忙指出问题所在。万分感谢!