2012-10-25 108 views
1

我已經在Context.xml(JNDI)中定義了DataSource,並且我想在Spring應用程序Context.xml中使用JPA事務管理器。因爲我使用的是tomcat服務器,所以我不想使用JTA Transaction。使用JNDI和JPA事務管理器進行Spring事務

任何人都可以幫助我我怎樣才能實現這個例子?我在DAO和服務中使用@transactional註釋。

問候 維傑

回答

0

下面是一個例子:

<?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:jee="http://www.springframework.org/schema/jee" 
     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/jee 
     http://www.springframework.org/schema/jee/spring-jee-3.0.xsd 
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 

    <!-- Provides access to the JNDI datasource --> 
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/jpetstore"/> 

    <!-- Defines transaction manager --> 
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
     <property name="dataSource" ref="dataSource"/> 
    </bean> 

    <!-- Enables transactional behavior --> 
    <tx:annotation-driven /> 

    <!-- other <bean/> definitions here --> 

</beans> 

使用<jee:jndi-lookup/>獲得訪問JNDI數據源。然後,將獲得的數據源參考傳遞給合適的PlatformTransactionManager,如DataSourceTransactionManager

此外,<tx:annotation-driven />應提供的@Transactional註釋被激活。

爲了更好地理解Spring的事務管理,我建議閱讀第10章Spring參考可用的here

+1

不要忘了'TX:annotationDriven' – Ralph

+0

@Reza感謝您的回覆 – VijayM

+0

@Reza但我面臨着以下問題org.springframework.beans.factory.BeanCreationException:錯誤創建名爲「purpleDS」豆:調用init方法失敗;嵌套異常是javax.naming.NameNotFoundException:名稱jdbc未綁定在此上下文中 – VijayM

0

您可以定義數據源:使用JndiObjectFactoryBean類。通過提供JNDI綁定名稱來定義數據源。

<!– Data Source JNDI –> 
<bean id=」dataSource」 class=」org.springframework.jndi.JndiObjectFactoryBean」> 
<property name=」jndiName」> 
<value>jdbc/SampleDS</value> 
</property> 
</bean> 
相關問題