JPA - 在不调用 persist() 的情况下保存更改 [英] JPA - saving changes without persist() invoked
问题描述
我们正在使用 JPA + Spring + EJB 的 Toplink 实现.在我们的一个 EJB 中,我们有这样的东西:
We are using Toplink implementation of JPA + Spring + EJB. In one of our EJBs we have something like this:
public void updateUser(long userId, String newName){
User u = em.get(User.class, userId);
u.setName(newName);
// no persist is invoked here
}
所以,基本上这个 updateUser()
方法应该使用给定的 userId
更新用户的名称.但是这个方法的作者忘记调用em.persist(u)
.
So, basically this updateUser()
method is supposed to update the name of a user with the given userId
.
But the author of this method forgot to invoke em.persist(u)
.
最奇怪的是它运行良好.怎么可能?我 100% 确定不调用 em.persist()
或 em.merge()
就不可能将更改保存到数据库中.他们可以吗?有没有可能发生这种情况?
And the strangest thing is that it works fine. How can it be? I was 100% sure that
without invoking em.persist()
or em.merge()
there is no way that changes could have been saved into database. Could they? Is there any scenario when this could happen?
推荐答案
您正在使用托管实体.如果实体没有因为其实体管理器关闭而分离,则在刷新/关闭会话并提交事务时,对实体所做的所有更改都会反映到数据库中.
You're working with a managed entity. If the entity does not become detached because its entity manager is closed, all changes done to the entity are reflected to the database when the session is flushed/closed and the transaction commited.
来自 Java EE 教程:
持久化实体的状态是同步到数据库时与实体发生的交易相关的提交.
The state of persistent entities is synchronized to the database when the transaction with which the entity is associated commits.
为清晰和解释进行编辑:因此,实体在其生命周期中可能处于三种不同的模式:
Edit for clarity and explanation: So there are three distinct modes that an entity could be in during its lifecycle:
- 未保存:实体已被实例化,但
persist()
尚未被调用. - Managed:实体已使用
persist()
持久化,或从数据库加载,并与实体管理器会话相关联.刷新实体管理器会话时,对实体的所有更改都会反映到数据库中. - 分离:实体的实体管理器会话已关闭.对实体的更改不会自动反映到数据库中,但可以使用
merge()
命令显式合并.
- Unsaved: The entity has been instantiated, but
persist()
has not been called yet. - Managed: The entity has been persisted using
persist()
, or loaded from the database, and is associated with an entity manager session. All changes to the entity are reflected to the database when the entity manager session is flushed. - Detached: The entity's entity manager session was closed. Changes to the entity will not be reflected to the database automatically, but can be merged explicitly using the
merge()
command.
这篇关于JPA - 在不调用 persist() 的情况下保存更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!