spring mvc+hibernate4事务控制

问题描述

spring mvc+hibernate4事务控制
 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时会报错,理论上应该都不提交事物。但实际上第一条执行了之后就提交事物了,不知道是我框架问题还是我写的问题,求大神帮忙指出问题所在。万分感谢!

解决方案

问题呢?说一下问题是什么吧~

解决方案二:

@Transactional注解是默认遇到throw new RuntimeException("...");会回滚,你的test方法中运行的话有没有进入异常分支呢,如果没有的话,那么你描述的现象就是正常的啊。

解决方案三:

在controller-servlet.xml中添加:

解决方案四:

在controller-servlet.xml中添加:

解决方案五:

在controller-servlet.xml中添加:

 <tx:annotation-driven transaction-manager="transactionManager" />
时间: 2024-09-08 10:00:31

spring mvc+hibernate4事务控制的相关文章

spring mvc +hibernate4事务控制问题求大神解答

问题描述 spring mvc +hibernate4事务控制问题求大神解答 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="

spring data jpa + spring mvc的事务控制问题

问题描述 spring data jpa + spring mvc的事务控制问题 问题大概是这样的,如下@Transactionalpublic void save(A a){ a = aRepository.save(a); B b = new B();b.setAId(a.getId());bRepository.save(b); }这样是获取不到a对象的id的,因为方法没有执行完,这个事务没有提交,数据没有更新到数据库,请问如果我想在save之后通过返回的对象就能拿到主键需要怎么做,事务是

spring mvc+mybatis 事务控制不起作用

问题描述 用的是spring mvc和mybatis框架.数据库是mysql.然后发现事务配置了不起作用..业务逻辑是新增用户,用户新增成功之后再在其他表插入一条对应的用户角色关联信息.现在问题是假如用户插入成功之后..插入对应的用户角色关联信息出错后,用户那条新增记录不能自动删除.看了很多人说是因为@service提前扫描的问题.那个我改过了.还有说是表的引擎不是InnoDB.但是我们建的表是InnoDB.还有说要抛出RuntimeException.我也抛出了..但是还是没用.没办法.请大家

sping hibernate 事务-spring注解方式事务控制没有回滚

问题描述 spring注解方式事务控制没有回滚 项目中使用到了hibernate以及spring事务控制,在service层增加事务控制但是遇到异常没有回滚. 代码如下: 配置文件 <?xml version="1.0" encoding="UTF-8"?> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springfr

spring mvc+spring3+hibernate4的事务不会自动清楚session缓存

问题描述 spring mvc+spring3+hibernate4的事务不会自动清楚session缓存 没有手动清缓存,就不执行插入SQL了手动清缓存的话,就能添加成功. 有知道原因的大神吗!!! 解决方案 没遇到过这种情况,tomcat么 解决方案二: 你这个没有加上事务,save时不会自动flush,加了事务之后commit时会自动flush.你配置事务了吗? 解决方案三: 贴出事务来看看,会不会没起作用

spring事务控制转账问题

问题描述 spring事务控制转账问题 例:A账户金额有1000元,另有B账户,C账户:现有两个独立事务同时进行: 1,将A账户的1000块钱转到B账户: 2,将A账户的1000块钱转到C账户: 事务的操作:A,-1000 B/C,+1000: 是不是会存在这种情况: 执行事务时,由于没有真正修改数据库,两个事务都是合法: 执行完事务,实际保存数据时,后保存数据A账户钱数会报错(金额不会修改),而C账户钱会增加: 导致,B,C账户增加总和大于A账户减少的金额? 解决方案 spring事务问题:没

ibatis+spring mvc事务不能回滚

问题描述 最近才接触spring MVC和ibates,现在我需要配置事务回滚,但是倒腾了一天还是不行,熟悉的朋友帮忙看看: applicationContext.xml文件配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w

spring mvc 事务,操作多张表的时候,异常不回滚,求大神帮忙啊

问题描述 spring mvc 事务,操作多张表的时候,异常不回滚,求大神帮忙啊 @Override @Transactional(rollbackFor=Exception.class) public Boolean saveXkcq(String qian,String xh, Xk_cqb cqb, Rw_xkb rwXkb, Xk_xkb xkb) { Boolean type = false; try { if(qian!=null && qian.length()>0){

Spring MVC 更灵活的控制 json 返回

这篇文章主要讲 Spring MVC 如何动态的去返回 Json 数据 在我们做 Web 接口开发的时候, 经常会遇到这种场景. 两个请求,返回同一个对象,但是需要的返回字段并不相同.如以下场景 /** * 返回所有名称以及Id */ @RequestMapping("list") @ResponseBody public List<Article> findAllNameAndId() { return articleService.findAll(); } /** *