Seam 建议在有状态 session Bean 中使用Extended 持久性上下文,以实现 Seam 管理的持久性。
我不清楚上述建议是否对我们希望使用 Seam 管理事务的方式产生任何影响。这是因为我们的架构不同。我们在 Stateless EJB 中有以下持久性上下文:
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class CrudServiceBean implements CrudService {
@PersistenceContext(type = PersistenceContextType.TRANSACTION)
private EntityManager em;
...
}
我们的 DAO 调用上述 CrudServiceBean 是无状态 EJB(其中一些也是 Seam 组件),带有 @TransactionAttribute(TransactionAttributeType.REQUIRED)。因此,我们的事务处理由容器 (WebLogic) 而不是 Seam。
但是,我们现在需要满足以下场景:我们需要有一个前端 Seam 组件(非 EJB)调用多个 DAO(EJB)方法并将它们全部包装在一个单笔交易。如果我理解正确的话,我们需要有 Seam 管理的事务。
我们能否像我描述的场景那样拥有 Seam 管理的事务,而没有 Seam 管理的持久性上下文?还是两者不相关?
最佳答案
如前所述
We need to have a front-end Seam component (non-EJB) invoke multiple DAO (EJB) methods and wrap all of them in a single transaction
但是
Our transactions are handled by the container - Also called Container Managed Transaction (The container Takes care of calling begin and commit method used by each underlying resource-manager Transaction)
第一个问题是您有一个非 EJB 调用多个 DAO 的场景,每个 DAO 都是一个 EJB。你可以想到
@Name("nonEjbComponent")
public class NonEjbComponent {
private @In DaoEjbComponent daoEjbComponent;
private @In OtherDaoEjbComponent otherDaoEjbComponent;
private @In AnotherDaoEjbComponent anotherDaoEjbComponent;
private @In UserTransaction userTransation;
public void wrapperAllOfThem() {
userTransation.begin();
daoEjbComponent.save(someEntity);
otherDaoEjbComponent.update(otherEntity);
anotherDaoEjbComponent.delete(anotherEntity);
userTransation.commit();
}
}
但是 Java EE 规范 3.0 声明
The enterprise bean with Either bean-managed or container-managed transaction demarcation must be a session bean or a message-driven bean.
所以你不能使用上面的场景。并且因为您所有的 DAO 都使用容器管理的事务,Java EE 规范不允许您同时使用容器管理和 bean 管理的事务
所以解决方案是
将所有 DAO 包装在一个 EJB 无状态 session bean 中,其事务由容器管理。它将表现得像一个委托(delegate)组件
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
@Name("wrapperStateless")
public class WrapperStatelessImpl implements WrapperStateless {
private @In DaoEjbComponent daoEjbComponent;
private @In OtherDaoEjbComponent otherDaoEjbComponent;
private @In AnotherDaoEjbComponent anotherDaoEjbComponent;
public void wrapperAllOfThem() {
daoEjbComponent.save(someEntity);
otherDaoEjbComponent.update(otherEntity);
anotherDaoEjbComponent.delete(anotherEntity);
}
}
在非 EJB 组件中,使用
@Name("nonEjbComponent")
public class NonEjbComponent {
private @In WrapperStateless wrapperStateless;
public void wrapperAllOfThem() {
wrapperStateless.wrapperAllOfThem();
}
}
关于java - Seam 管理的事务操作指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3256342/