2011-12-12 71 views
0

Spring + Hibernate的:事務提交,但我使用實現Hibernate持久下面的服務層類數據不保留

public class AccountsManagerImpl implements IAccountsManager { 
    private static Logger log = LoggerFactory.getLogger(AccountsManagerImpl.class); 

    private final SessionFactory sessionFactory; 
    private AccountDao accountDao; 

    public AccountsManagerImpl(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
     accountDao = new AccountDao(sessionFactory); 
    } 

    @Override 
    public void createAccount(final Account account) { 
     runInTransaction(new Runnable() { 
      public void run() { 
       accountDao.add(account); 
      } 
     }); 
    } 

    @Override 
    public void modifyAccount(final Account account) { 
     runInTransaction(new Runnable() { 
      public void run() { 
       accountDao.update(account); 
      } 
     }); 
    } 

    @Override 
    public void deleteAccount(final Account account) { 
     runInTransaction(new Runnable() { 
      public void run() { 
       accountDao.remove(account); 
      } 
     }); 
    } 

    private void runInTransaction(Runnable runnable) { 
     Session session = sessionFactory.getCurrentSession(); 
     Transaction tx = null; 
     try { 
      tx = session.beginTransaction(); 
      runnable.run(); 
      tx.commit(); 
     } 
     catch(Exception e) { 
      log.error("Exception during transaction, rolling back", e); 
      if(tx != null && tx.isActive()) { 
       try { 
        tx.rollback(); 
       } 
       catch(Exception e2) { 
        log.error("Failed to rollback transaction", e2); 
       } 
       throw new IllegalStateException("Transaction failed", e); 
      } 
     } 
    } 

} 

這個類,與實體類一起,是在一個單獨的庫( .jar),即插入到webapp中。 Web應用程序使用這個類有以下Spring配置:

<?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:mvc="http://www.springframework.org/schema/mvc" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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.xsd 
    "> 

    <!-- Scans within the base package of the application for @Components to configure as beans --> 
    <bean id="placeholderConfig" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
     <property name="location" value="classpath:db.properties"/> 
    </bean> 

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource"/> 
     <property name="schemaUpdate" value="true"/> 
     <property name="packagesToScan"> 
      <list> 
       <value>com.rcslabs.webcall.server.model</value> 
      </list> 
     </property> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.connection.autocommit">false</prop> 
       <prop key="hibernate.show_sql">false</prop> 
       <prop key="hibernate.format_sql">false</prop> 
       <prop key="hibernate.dialect">${db.dialect}</prop> 

       <prop key="hibernate.cache.use_query_cache">false</prop> 
      </props> 
     </property> 
    </bean> 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
      destroy-method="close"> 
     <property name="driverClassName" value="${db.driver}"/> 
     <property name="url" value="${db.url}"/> 
     <property name="username" value="${db.username}"/> 
     <property name="password" value="${db.password}"/> 
    </bean> 

    <bean 
      class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 

     <bean class="com.rcslabs.webcall.server.impl.AccountsManagerImpl"> 
     <constructor-arg ref="sessionFactory"/> 
    </bean> 

</beans> 

當的createAccount方法被調用時,交易將提交的對象得到它的從數據庫序列號,但數據不保留(沒有INSERT,該表爲空):

2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - begin 
2011-12-12 14:45:22,932 DEBUG: org.hibernate.jdbc.ConnectionManager - opening JDBC connection 
2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - current autocommit status: true 
2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - disabling autocommit 
2011-12-12 14:45:22,934 DEBUG: org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) 
2011-12-12 14:45:22,936 DEBUG: org.hibernate.SQL - select nextval ('hibernate_sequence') 
2011-12-12 14:45:22,940 DEBUG: org.hibernate.id.SequenceGenerator - Sequence identifier generated: BasicHolder[java.lang.Long[12]] 
2011-12-12 14:45:22,940 DEBUG: org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1) 
2011-12-12 14:45:22,940 DEBUG: org.hibernate.event.def.AbstractSaveEventListener - generated identifier: 12, using strategy: org.hibernate.id.SequenceGenerator 
2011-12-12 14:45:22,946 DEBUG: org.hibernate.transaction.JDBCTransaction - commit 
2011-12-12 14:45:22,947 DEBUG: org.hibernate.transaction.JDBCTransaction - re-enabling autocommit 
2011-12-12 14:45:22,947 DEBUG: org.hibernate.transaction.JDBCTransaction - committed JDBC Connection 
2011-12-12 14:45:22,947 DEBUG: org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources! 

什麼是錯?如何正確保存數據?

編輯:

我不喜歡在圖書館使用Spring聲明式事務(@Transactional),並取決於與Spring類。我只是想將正確的SessionFactory傳遞給管理器並使其工作。

回答

3

爲什麼不使用:

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

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" 
    p:entityManagerFactory-ref="entityManagerFactory" 
    p:dataSource-ref="dataSource" /> 

,那麼你可以簡單地使用了@Transactional註釋上述任何方法你想包裹在一個交易?

@Override 
@Transactional 
public void createAccount(final Account account) { 
    accountDao.add(account); 
} 
+0

我不想依賴庫中的Spring註釋。這纔是重點。 – weekens

+1

好,但也許你應該添加這個問題到你的問題呢?只是一個建議;-) – Mick

+0

不得不使用聲明性事務,因爲延遲加載的問題。希望我有一種方法可以在庫之外的某處配置Spring-Hibernate。 – weekens

0

我沒有在你的應用程序中發現問題,但我可以回答第二個問題:「如何正確保存數據?」

使用Spring Transaction Template,而不是一些自己的實現。

+0

它將庫綁定到Spring事務基礎結構。 – weekens

+0

@weekens:是的,它的確如同SessionFactory一樣將你綁定到Hibernate。 – Ralph

+0

你是對的。我可以將庫綁定到Hibernate(以及JPA)。但是Spring只是我想在webapp項目中使用的東西。這給了更多的靈活性。 – weekens

1

通過org.springframework.orm.hibernate3.HibernateTransactionManager的代碼看着。

在tx.commit()解決問題之前添加session.flush()。

+1

雖然這仍然會導致延遲加載問題。也許有一個更好的解決方案,而不綁定到Spring? – weekens