การจัดการ transaction ด้วย spring
posted on 03 Dec 2008 09:17 by sonicneo in Springก่อนอื่นก็ต้องมา config ที่ไฟล์ xml ซะก่อนนะ ต่อไปนี้เป็นการกำหนด trasaction สำหรับ Hibernate นะครับ
เริ่มแรกก็ประกาศบีนชื่อ hibernateTxManager ซึ่งเป็นคลาส HibernateTransactionManager จากนั้นก็ injection sessionFactory เข้าไปด้วย
จากนั้นประจุดตัดเพื่อบอกให้รู้ว่าต้องการทำ trasaction ที่ service อะไร ในที่นี้สามารถกำหนดได้ว่าให้เลือกที่
ทั้ง package โดยเีขียนไว้ใน tag aop:config
จากนั้นเป็นการกำหนดว่าต้องการให้ method ที่ชื่อขึ้นต้นด้วยอะไรบ้างที่จะทำ trasaction โดยเขียนไว้ใน
tag tx:advice
เพียงเท่านี้เราก็สามารถกำหนดการทำ trasaction ด้วย Spring โดยที่เราไม่ต้องเขียน Code เพื่อจัดการ trasaction เองเลย ที่เหลือเราก็เพียงแค่เขียนคลาสธรรมดา ปล่อยให้เป็นหน้าที่ของ 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: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">
<!-- SessionFactory, DataSource, etc. omitted -->
<bean id="hibernateTxManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<aop:config>
<aop:pointcut id="hibernateUrCmitServiceMethods"
expression="execution(* com.ais.itams.ur.cmit.spring.hibernate.persistance.service.*.*(..))" />
<aop:advisor advice-ref="txAdviceHibernate" pointcut-ref="hibernateUrCmitServiceMethods" />
</aop:config>
<tx:advice id="txAdviceHibernate" transaction-manager="hibernateTxManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" propagation="REQUIRED" read-only="false" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
</beans>
edit @ 3 Dec 2008 09:35:39 by sonicneo