hibernate 不用事务,也提交到了数据库,帮忙看看

配置 spring mvc + hibernate , 我在配置文件配置了注解的事务,但是controller 没写上@transaction 数据竟然插入到了数据库, 我都把事务的配置文件给干掉了也是提交到了数据库, 看了半天找不到, 帮忙看看,谢谢! 用的是sql server 数据库

 

<?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_3_0.xsd"
    id="WebApp_ID" version="3.0">
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/spring/spring.xml</param-value>
    </context-param>
    
    <!-- 配置DispatcherServlet-->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/spring/springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>    
    
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
    <!-- 监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 编码过滤器 -->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
    
    <!-- security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> 
    <welcome-file-list>
        <welcome-file>index.do</welcome-file>
    </welcome-file-list>
    
</web-app>

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.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-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.xsd">

    <context:annotation-config />

    <!-- 自动扫描的包名 -->
    <context:component-scan base-package="com.belief.web.controller.**"></context:component-scan>
    
    <bean id="springContextUtil" class="com.belief.web.common.util.SpringContextUtil" ></bean>

     <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
        <property name="basename">
            <value>/WEB-INF/message/message</value>
        </property>
        <property name="cacheSeconds">
            <value>-1</value>
        </property>
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>
    
    <!-- 默认的注解 -->
    <!-- <mvc:annotation-driven/> -->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <!-- <property name="interceptors">
            <list>
                <bean class="com.belief.web.common.MyIntercepter"></bean>
                国际化拦截器配置
                <bean id="localResolver" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
            </list>
        </property> -->
    </bean>
    <!-- 手动注册注解 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="byteArray_hmc" />
                <ref bean="string_hmc" />
                <ref bean="resource_hmc" />
                <ref bean="source_hmc" />
                <ref bean="xmlAware_hmc" />
                <ref bean="jaxb2Root-hmc" />
                <ref bean="jackson_hmc" />
            </list>
        </property>
    </bean>
    <bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"></bean>
    <bean id="string_hmc" class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name ="supportedMediaTypes">  
            <list><value>text/plain;charset=UTF-8</value></list>  
        </property>  
    </bean>
    <bean id="resource_hmc" class="org.springframework.http.converter.ResourceHttpMessageConverter"></bean>
    <bean id="source_hmc" class="org.springframework.http.converter.xml.SourceHttpMessageConverter"></bean>
    <bean id="xmlAware_hmc" class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"></bean>
    <bean id="jaxb2Root-hmc" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"></bean>
    <bean id="jackson_hmc" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    
    <!-- 试图解析 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/pages/" >
        <!-- <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=""></property> -->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
    </bean>
    
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="cookieName" value="clientlanguage"/>
        <property name="cookieMaxAge">
            <value>2592000</value>
        </property>
    </bean>
    
    <!-- 拦截器 -->
    <mvc:interceptors>
        <bean class="com.belief.web.common.intercepter.MyIntercepter"></bean>
        <!-- 国际化拦截器配置 -->
        <bean id="localResolver" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
        <!-- 单独URL配置拦截器 -->
        <!-- <mvc:interceptor>
            <mvc:mapping path="/user/*" />
            <bean class="com.belief.web.common.MyIntercepter"></bean>
        </mvc:interceptor> -->
    </mvc:interceptors>
    
    <!-- 静态资源文件的访问,方案一 -->
    <mvc:default-servlet-handler/>
    
    <!-- 静态资源文件的访问,方案二  cache-period 可以使得静态资源进行web cache -->
    <!-- <mvc:resources location="/images/" mapping="/images/**" cache-period="31556926" />
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/> -->
    
    <!-- 全局异常处理 -->
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView">
            <value>/error/exception.jsp</value>
        </property>
        <!-- 值:“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”,是“SimpleMappingExceptionResolver类的全限定名”。
        这个值不是随便写的。  因为我在log4j的配置文件中还要加入
        log4j.logger.org.springframework.web.servlet.handler.SimpleMappingExceptionResolver=WARN,
        保证这个级别是warn的日志一定会被记录,即使log4j的根日志级别是ERROR。 -->
        <property name="warnLogCategory">    
            <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>  
        </property>   
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.IllegalArgumentException">/error/exception.jsp</prop>
            </props>
        </property>
    </bean>
    
</beans>

 

<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
    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: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-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/tx   
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
         http://www.springframework.org/schema/aop  
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> 

    <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource" depends-on="propertyConfigurer">
        <property name="driver" value="${jdbc.driverClassName}"></property>
        <property name="driverUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <!-- 最大连接数(默认5个) -->
        <property name="maximumConnectionCount">
            <value>60</value>
        </property>
        <!-- 最小连接数(默认2个) -->
        <property name="minimumConnectionCount">
            <value>10</value>
        </property>
        <!-- 同时构建节流 -->
        <property name="simultaneousBuildThrottle">
            <value>10000</value>
        </property>
        <!-- 最少保持的空闲连接数(默认2个) -->
        <property name="prototypeCount">
            <value>5</value>
        </property>
        <!-- 使用前测试 -->
        <property name="testBeforeUse">
            <value>true</value>
        </property>
        <!-- 测试使用的sql -->
        <property name="houseKeepingTestSql">
            <value>select getDate()</value>
        </property>
        <!-- 最大活动时间(超过此时间线程将被kill,默认5分钟) -->
        <property name="maximumActiveTime">
            <value>7200000</value>
        </property>
        <!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒) -->
        <!-- <property name="houseKeepingSleepTime" value="${proxool.hourseKeepingSleepTime}"/> -->
    </bean>

    <!-- 可以在XML配置文件中加入外部属性文件 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>WEB-INF/config.properties</value>
        </property>
    </bean>   

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" depends-on="propertyConfigurer">
        <property name="dataSource">
            <ref local="dataSource" /> 
        </property>
        <property name="mappingResources">
            <list>
                <value>com/belief/web/biz/user/User.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <!-- Oracle -->
                <!-- <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> -->
                <!-- Sql Server -->
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
                <prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>             
                <prop key="hibernate.query.substitutions">true 1, false 0</prop>
                <!-- 开启二级缓存  -->
                <!-- <prop key="hibernate.cache.use_second_level_cache">true</prop> -->
                <!-- 设置缓存类  -->
                <!-- <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> -->
                <!-- 否使用结构化的方式缓存对象 -->
                <!-- <prop key="hibernate.cache.use_structured_entries">true</prop> -->
                <!-- 是否缓存查询结果 -->
                <!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
            </props>
        </property>
    </bean>
    
    <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
       <property name="sessionFactory"><ref bean="sessionFactory"/></property>
    </bean>
    
    <!-- 配置事务 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" >
            <ref local="sessionFactory"/>
        </property>
    </bean>
    
    <!-- 注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    
    <bean id="dao" class="com.belief.web.common.dao.Dao">
    </bean>
    
    <bean id="daoFactorySupport" class="com.belief.web.common.dao.DaoFactorySupport">
    </bean>
</beans>

 

@RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(HttpServletRequest request,HttpServletResponse response){
        Dao dao = DaoFactory.getInstance().getDao();
        User user = new User();
        user.setName("hibernate");
        user.setState(PojoState.NORMAL);
        user.setVersion(1);
        dao.save(user);
        return "redirect:/index.do";
    }

 

public class User extends BaseEntity
{

    private static final long serialVersionUID = 2274719953051444808L;

    /** 员工姓名 */
    private String name;
    /** 用户组 */
    private String userGroup;

 

<?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="com.belief.web.biz.user.User" table="auth_user">
        <!-- <cache usage="read-write" /> -->
        <id name="id" column="user_id" unsaved-value="null">
            <generator class="identity" />
        </id>
        <property name="version" column="version" />
        <property name="createTime" column="create_time" />
        <property name="updateTime" column="update_time" />
        <property name="userGroup" column="user_group" />
        <property name="penddingReadAnnonAmt" column="pendding_read_annon_amt" />
        <many-to-one name="createUser" column="create_user" class="com.belief.web.biz.user.User" />
        <many-to-one name="updateUser" column="update_user" class="com.belief.web.biz.user.User" />
        <property name="state" type="com.belief.web.common.entity.PojoStateType" />
        <property name="name" />
    </class>
</hibernate-mapping>

 

package com.belief.web.common.dao;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.belief.web.common.entity.BaseEntity;

@SuppressWarnings("unchecked")
public class Dao extends HibernateDaoSupport{

    public <T extends BaseEntity>T get(Class<? extends BaseEntity> cls,String id){
        return (T) this.getHibernateTemplate().get(cls, id);
    }
    
    public List<BaseEntity> find(Class<? extends BaseEntity> cls){
        return this.getHibernateTemplate().find("FROM "+cls.getName());
    }
    
    public void save(BaseEntity baseEntity){
        getHibernateTemplate().save(baseEntity);
    }
    
}

 

package com.belief.web.common.dao;


public class DaoFactory {

    private static final DaoFactory instance = new DaoFactory();

    public static DaoFactory getInstance() {
        return instance;
    }
    
    Dao dao;

    public Dao getDao() {
        return dao;
    }
    
}

 

package com.belief.web.common.dao;


public class DaoFactorySupport {

    public void setDao(Dao dao){
        DaoFactory.getInstance().dao = dao;
    }
    
    
}

 

4个回答

我想知道楼主为什么觉得没有事物配置就无法插入到数据库中呢~

weixin_42506784
weixin_42506784 我知道我上面的问题在oracle肯定是不存在的, sql server 好像是自动提交的事务, 我应该明白了,谢谢,
6 年多之前 回复
zm112358
zm112358 看了楼主的代码,我觉得楼主亦非初学者,应该已经有开发的经验,所以应该了解到有些数据库是没有事物支持的比如说mysql的默认的引擎就是不支持事物,那么即便是你配置了事物也无法实现对事物的控制。所以说事物的控制和你的配置应该没有关系。
6 年多之前 回复
weixin_42506784
weixin_42506784 sql server 本身是不需要提交事务,就能插入数据的, 我在后面用hibernate ,我记得之前写的, 简单的例子,hibernate 的事务需要, start 然后要 commit的,这样数据才会进入到数据库。 或者是我的理解不够深, 嘿嘿, 请指教,
6 年多之前 回复

我想知道楼主为什么觉得没有事物配置就无法插入到数据库中呢~ +1

+10086

使用hibernate不配事务也可以入库的,,还记得用jdbc的时候,。。默认是AutoCommit=true的。。hibernate封装了jdbc。。默认AutoCommit=true。。明白了吗

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问