The Transaction Context Problem is base on you can’t pass the transaction from one Bean to another. For example, FinacialService and DeptService has their own trnsaction management. If DeptService failed, we can only rollback DeptService. This is violated Transaction’s ACID principle.

class EmployeeServiceBean imeplements EmployeeService {
	public void hire(){
		FinacialService.insert();
		DeptService.insert();
	}
}

Using Spring, we can add transaction proxy and AOP to make this method as Unit of work.

	<bean id="employeeService" class="com.myapp.EmployeeServiceBean">
		...
	</bean>

	<bean id="employeeService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
		<property name="transactionManager" ref="trxManager"/>
		<property name="target" ref="employeeService"/>
		<property name="transactionAttributes">
			<props>
				<prop key="*">PROPAGATION_REQUIRED, -Exception</prop>
			</props>
		</property>
	</bean>

Using EJB3, we see it’s simple.

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class EmployeeServiceBean {
	@Resource
	private SessionContext context;
	...
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void hire(){
		try {
			FinacialService.insert();
			DeptService.insert();
		} catch (ApplicationException ae) {
			context.setRollbackOnly();
		}
	}
}
Advertisements