本文介绍了玩!框架立即保存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在播放!如果您这样称呼:

In Play! if you call this:

void method()
{
User u = User();
u.name = "bob";
u.save();
while(true){/* endless loop */}
}

实际上什么也不会保存到数据库中(Play!类需要腾出双手来刷新保存内容.)

Nothing will actually be saved into the db (The Play! class needs to get the hand back to flush the saves.)

如何强制执行冲洗或使其在保存时自动冲洗?

How do I have to proceed in order to either force a flush or to make it automatically flush at save ?

推荐答案

您的更改在数据库中不可见的原因是该事务尚未提交,因此其他事务无法看到

The reason why your changes are not visible in the database, is that the transaction is not yet commited and so other transactions can't see your changes (at least in a good database like PostgreSQL, Oracle, MSSQL, DB2).To make your changes seen, you'll have to commit your transaction before it enters the infinite loop, like this:

void method()
{
    User u = User();
    u.name = "bob";
    u.save();
    JPA.em().flush();
    JPA.em().getTransaction().commit();

    while(true){/* endless loop */}

}

如果您想在无限循环内或之后访问数据库(如果有中断条件),则必须开始进行新的事务,否则将从休眠中获取异常.像这样

If you want to access your database inside the infinite loop or after it (if you have a break condition), you'll have to begin a new transaction or you'll get exceptions from hibernate. Do this like this

void method()
{
    User u = User();
    u.name = "bob";
    u.save();
    JPA.em().flush();
    JPA.em().getTransaction().commit();

    while(true){
      // do some stuff

      /* TRANSACTIONAL BLOCK BEGINS */
      JPA.em().getTransaction().begin();
      try{
          // do some stuff
          // fetching, updating, deleting, whatever

          JPA.em().getTransaction().commit();
      }
      catch (Exception e)
      {
          // if an error occurs, rollback the transaction
          JPA.em().getTransaction().rollback();
      }
      /* TRANSACTIONAL BLOCK ENDS */
      // do some other stuff
    }
   // copy the TRANSACTIONAL BLOCK from above, if you want to do stuff after the "infinite loop" as well.
}

重要的是,您要在循环中提交回滚该事务,如果从那里开始,则否则会遇到太多未完成事务的问题很快.

It's important that you either commit or rollback the transaction in the loop, if you start it there, as else you'll run into problems with too many open transactions soon.

这篇关于玩!框架立即保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:19