Groovy Sql使用Spring的事务管理


    Grails如果不想用Hibernate的东东,可以直接用Sql

配置部分可以参考——

?

http://www.iteye.com/topic/11506?page=3

?

使用的代码:(配置、类似spring transactionTemplate、Closure = Callback)

?

?

	<bean id="defaultDsTarget" lazy-init="true"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName"><value>${db_local_driver}</value></property>  
		<property name="url"><value>${db_local_url}</value></property>  
		<property name="username"><value>${db_local_user}</value></property>  
		<property name="password"><value>${db_local_pwd}</value></property> 
	</bean>
	<bean id="defaultDs" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
		<constructor-arg>
			<ref bean="defaultDsTarget" />
		</constructor-arg>
	</bean>
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource">
			<ref bean="defaultDsTarget"/>
		</property>
	</bean>

?

?

?

	static DataSource getDs(){
		final dsBeanName = 'defaultDs'
		def context = AppContext.getContextBiz()
		return context.getBean(dsBeanName)
	}

	// use spring platform indenpendent TransactionManager
	static DataSourceTransactionManager getTm(){
		def context = AppContext.getContextBiz()
		return context.getBean('transactionManager')
	}

	// not available in weblogic
	static void withTrans(Closure callback){
		def tm = getTm()
		def transDef = new DefaultTransactionDefinition()
		def status = tm.getTransaction(transDef)
		try {
			callback.call()
			tm.commit(status)
		}catch (ex) {
			log.error('DSManager withTrans failed!', ex)

			tm.rollback(status)
			throw ex
		}
	}

?




			DSManager.withTrans{
				def dao = new YourDAO() // use defaultDs from spring beanfactory
			}

?
?

 

你可能感兴趣的:(java,工作,groovy)