问题描述
正在播放!如果您这样称呼:
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 ?
推荐答案
您的更改在数据库中不可见的原因是该事务尚未提交,因此其他事务无法看到您的更改(至少在PostgreSQL,Oracle,MSSQL,DB2等良好的数据库中).为了使您的更改可见,您必须在事务进入无限循环之前进行提交,如下所示:
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.
这篇关于玩!框架立即保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!