grails中有个Service支持事务操作,但你如果想用Spring的事务,可以在grails-app/spring/resources.xml中加入spring的事务声明,如下所示:
resource.xml 代码
- <?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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
-
-
- <bean id="userImpl" class="transaction.UserImpl">
- <property name="sessionFactory" ref="sessionFactory"/>
- </bean>
-
-
- <tx:advice id="txAdvice" transaction-manager="txManager">
-
-
- <tx:attributes>
-
-
-
-
- <tx:method name="*"/>
- </tx:attributes>
- </tx:advice>
-
-
-
- <aop:config proxy-target-class="true">
- <aop:pointcut id="fooServiceOperation" expression="execution(* transaction.*.*(..))"/>
- <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
- </aop:config>
-
-
-
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/OA"/>
- <property name="username" value="root"/>
- <property name="password" value=""/>
- </bean>
-
-
-
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource"/>
-
- </bean>
-
- <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory"/>
- </bean>
-
-
-
-
- </beans>
UserImpl.groovy 代码
- package transaction
-
- import com.jr.nj.hibernate.Event
- import org.hibernate.SessionFactory
- import org.hibernate.Session
- import org.springframework.orm.hibernate3.HibernateTemplate
-
-
- class UserImpl {
- def sessionFactory
- def save(params) throws Exception {
- def event =new Event()
- event.setDate new Date()
- event.setTitle 'aaa'
- HibernateTemplate ht = new HibernateTemplate(sessionFactory);
- ht.save event
- def event2 =new Event()
- event2.setDate new Date()
- event2.setTitle 'bbb'
- ht.save event2
- throw new RuntimeException("事务测试")
- }
- }
其中,
Event可以是java定义的持久类或者groovy定义的domain。