JPA-保存更改而无需调用persist() [英] JPA - saving changes without persist() invoked

查看:334
本文介绍了JPA-保存更改而无需调用persist()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用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方法应使用给定的ID更新用户名. 但是该方法的作者忘记了调用em.persist(u);

So, basically this updateUser method is supposed to update the name of user with given id. But 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 a 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().
  • 受管理的:该实体已使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆