struts+spring+hibernate无法插入数据库数据的问题

时间:2022-03-08 21:39:36

用spring,hibernate发现无法往数据库里插入数据。其他一切正常,既不报exception,控制台sql又打出来了。试了无数种方法仍不能解决,郁闷。。。。。。。。

忽然灵机一动,只用hibernate的话,添加或修改数据需要commit一下,会不会与此有关?

想到就试,在addOrUpdate后,加一句super.getSession().beginTransaction().commit();     OK,搞定。

回过头来查原因,原来在spring的配置文件中加载hibernate的配置是这样的:

<bean id="sessionFactory"
   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="configLocation"
    value="classpath:hibernate.cfg.xml">
   </property>
</bean>

换句话说,是使用了hibernate本身的配置文件,所以特性呈现为hibernate而不是spring。

把该配置文件改为

<bean id="sessionFactory"
   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource">
    <ref local="dataSource"/>
   </property>
   <property name="mappingResources">
    <list>
     <value>xxx.hbm.xml</value>
    </list>
   </property>  
   <property name="hibernateProperties">  
    <props>   
     <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
     <prop key="hibernate.show_sql">true</prop>
     <prop key="hibernate.generate_statistics">true</prop>
     <prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
    </props>  
   </property>
</bean>

后,就不需要手动commit了。


或在不改变原有配置文件的基础上,添加自动提交

<property name="connection.autocommit">true</property> 也可以