【发布时间】:2011-11-08 11:56:53
【问题描述】:
在我们的 J2EE 应用程序中,我们使用 EJB-3 有状态 bean 来允许前端代码创建、修改和保存持久实体(通过 JPA-2 管理)。
看起来像这样:
@LocalBean
@Stateful
@TransactionAttribute(TransactionAttributeType.NEVER)
public class MyEntityController implements Serializable
{
@PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager em;
private MyEntity current;
public void create()
{
this.current = new MyEntity();
em.persist(this.current);
}
public void load(Long id)
{
this.current = em.find(MyEntity.class, id);
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void save()
{
em.flush();
}
}
非常重要,为了避免过早提交,事务中只有save() 方法,所以如果我们调用create(),我们不会在数据库中插入任何内容。
奇怪的是,在save() 方法中,我们必须调用em.flush() 才能真正命中数据库。事实上,我试过了,发现我们也可以调用em.isOpen()或em.getFlushMode(),以及任何与“em相关”的东西。
我不明白这一点。由于save() 在事务中,我认为在方法结束时,事务将被提交,因此持久实体管理器会自动刷新。为什么我必须手动冲洗它?
谢谢, 泽维尔
【问题讨论】:
-
不需要
flush()。joinTransaction()应该足以将您的修改保存在您的事务方法中。
标签: java jpa persistence ejb flush