一尘不染

Spring 3.x和Hibernate 4中的事务管理

hibernate

您好我已经面对一堵墙,而我试图使用Spring 3.x和hibernate4.做交易管理
我搜索在互联网上,但有办法在hibernate3要做到这一点,没有那么多的hibernate4.
I”我很困惑,我不确定此设置是否有效。

我正在使用的东西…
Spring 3.x
Hibernate 4

我已经阅读了这些
http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html#transaction-
declarative spring,hibernate和声明式事务的实现:没有活动的事务
,还有更多事务 …

后续
我已经成功地运行了我的课程。我已添加proxy-target-class="true"

<aop:config>

但是我不确定这是否正在事务中运行。它说true我使用时

TransactionSynchronizationManager.isActualTransactionActive()

但是当我有意在save方法中引发错误时,它不会回滚。

编辑
如NimChimpsky所建议,我尝试通过Spring MVC(dispatcher servlet)调用相同的方法,它说

    Cannot convert value of type 
[$Proxy19 implementing kr.co.sgis.services.web.cooingbee.Crudable,org.springframework.aop.SpringProxy,
org.springframework.aop.framework.Advised] to required type
[test.TXTestDAO] for property 'dao': 
no matching editors or conversion strategy found

我希望我越来越近。

编辑
log4j这样说。

INFO : org.hibernate.Version - HHH000412: Hibernate Core {4.1.7.Final}
INFO : org.hibernate.cfg.Configuration - HHH000041: Configured SessionFactory: null
INFO : com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1bqomxn8s1l3dkxojzz69x|e4865ce, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bqomxn8s1l3dkxojzz69x|e4865ce, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://211.115.111.229:3306/yoursmart, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 50, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
INFO : org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
INFO : org.hibernate.engine.jdbc.internal.LobCreatorBuilder - HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
INFO : org.hibernate.engine.transaction.internal.TransactionFactoryInitiator - HHH000399: Using default transaction strategy (direct JDBC transactions)
INFO : org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory - HHH000397: Using ASTQueryTranslatorFactory

它会说' Configured SessionFactory: null''TransactionFactoryInitiator - HHH000399: Using default transaction strategy (direct JDBC transactions)'但是c3p0连接池如何初始化而不会出现错误?

我的spring应用程序上下文看起来像这样。

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

</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="****"></property>
    <property name="user" value="****"></property>
    <property name="password" value="****"></property>
    <property name="initialPoolSize"><value>3</value></property>
    <property name="minPoolSize"><value>3</value></property>
    <property name="maxPoolSize"><value>50</value></property>
</bean>

<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
</bean>


<tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
    <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>



<bean id="txDAO" class="test.TXTestDAO">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
<bean id="testTxService" class="test.TXTestService">
        <property name="dao" ref="txDAO"/>
    </bean>

hibernate.cfg.xml

         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
         <property name="connection.url">****</property>
         <property name="connection.username">****</property>
         <property name="connection.password">****</property>
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
         <property name="connection.pool_size">5</property>
         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
          <property name="hibernate.c3p0.min_size">5</property>
          <property name="hibernate.c3p0.max_size">20</property>
          <property name="hibernate.c3p0.timeout">300</property>
          <property name="hibernate.c3p0.max_statements">50</property>
          <property name="hibernate.c3p0.idle_test_period">3000</property>

TXTestDAO.java 我的DAO没有实现HibernateDAOSupport。我必须执行它吗?

public int save(CooingbeeFetchable bean) {
        // TODO Auto-generated method stub
        try{

            sessionFactory.getCurrentSession().getTransaction().begin();
            //Using sessionFactory is low level
            sessionFactory.getCurrentSession().save(bean);

            sessionFactory.getCurrentSession().getTransaction().commit();
            System.out.println("committed");

        }catch(Exception e){
            e.printStackTrace();
        }
        return 0;
    }

我的测试课程只是使用FileSystemResource进行测试。

public class Tester {       
public static void main(String[] args){

            FileSystemResource fSysSrc = new FileSystemResource("C:\\SGI_Project\\eclipseWorkspace\\SPSWeb\\WebContent\\WEB-INF\\SpringDispatcher-servlet.xml");
            BeanFactory xmlBeanFactory = new XmlBeanFactory(fSysSrc);
            TXTestService txDAO= (TXTestService) xmlBeanFactory.getBean("testTxService");

            TXTestBean bean = new TXTestBean();

            bean.setName("bodybody");
            txDAO.save(bean);

        }
    }






public class TXTestService implements Crudable{

    private TXTestDAO dao;

    public void setDao(TXTestDAO nDAO){
        dao = nDAO;
    }
public int save(CooingbeeFetchable bean) {
        // TODO Auto-generated method stub
        return dao.save(bean);
    }
}

到目前为止,我没有找到当前线程异常的会话。 我也试图不使用注释。 我感到很失落 @。@ !
你能指出我正确的方向吗?


阅读 218

收藏
2020-06-20

共1个答案

一尘不染

不推荐使用XMLBean工厂,如果可以的话,我建议您使用注释和最新最好的Spring版本(spring 3.2的测试功能很棒)。它将为您简化一些事情,Dao/存储库可能有此功能

@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;

@Transactional(propagation = Propagation.REQUIRED)
 public T save(final T o) {
        return (T) sessionFactory.getCurrentSession().save(o);
    }

然后可以将其本身注入,并在yr config中添加以下内容:

 <tx:annotation-driven transaction-manager="transactionManager"/>
2020-06-20