如何知道一个分离的 JPA 实体是否已经被持久化? [英] How to know if a detached JPA entity has already been persisted or not?

查看:21
本文介绍了如何知道一个分离的 JPA 实体是否已经被持久化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序的 Web UI 层中有一个 JPA 实体实例.我想随时知道这个实体是否已经保存在数据库中,或者它是否只存在于用户会话中.

I have a JPA entity instance in the web UI layer of my application. I'd like to know at anytime if this entity has been already persisted in database or if it is only present in the user session.

它将在业务层中,我将使用 entitymanager.contains(Entity) 方法,但在我的 UI 层中,我认为我需要一个额外的属性来指示实体是否已保存.如何实施?我目前正在考虑以下选项:

It would be in the business layer, I would use entitymanager.contains(Entity) method, but in my UI layer I think I need an extra attribute indicating whether the entity has been saved or not. How implement that ? I'm considering following option for the moment:

  • 具有由数据库设置的默认值的 JPA 属性,但会在每次更新后强制进行新的读取?
  • 在我的代码中手动设置的非 JPA 属性还是由 JPA 自动设置的?

有什么建议/其他建议吗?

Any advice / other suggestions ?

我将 JPA 1 与 Hibernate 3.2 实现一起使用,并且更愿意坚持标准.

I'm using JPA 1 with Hibernate 3.2 implementation and would prefer stick to the standard.

推荐答案

首先,让我们提醒一个实体的各种状态.来自 JPA 1.0 规范(在 3.2 实体实例的生命周期部分):

First, let's remind the various states of an entity. From the JPA 1.0 specification (in section 3.2 Entity Instance’s Life Cycle):

本节描述了用于管理的 EntityManager 操作实体实例的生命周期.一个实体实例可以被表征作为新的、管理的、分离的或已移除.

This section describes the EntityManager operations for managing an entity instance’s lifecycle. An entity instance may be characterized as being new, managed, detached, or removed.

  • 实体实例没有持久身份,并且还没有与持久化上下文相关联.
  • 托管实体实例是具有持久身份的实例当前与持久性上下文相关联的.
  • 分离实体实例是一个具有持久身份的实例不(或不再)与持久性上下文相关联.
  • 已删除实体实例是具有持久身份的实例,与持久性上下文相关联,计划从数据库中删除.
  • A new entity instance has no persistent identity, and is not yet associated with a persistence context.
  • A managed entity instance is an instance with a persistent identity that is currently associated with a persistence context.
  • A detached entity instance is an instance with a persistent identity that is not (or no longer) associated with a persistence context.
  • A removed entity instance is an instance with a persistent identity, associated with a persistence context, that is scheduled for removal from the database.

和图形说明:

所以,根据定义,一个分离的实体已经被持久化了,我实际上并不认为这是你真正的问题.现在,如果你想知道一个实体是否是(即没有任何持久的身份),那么这个:

So, by definition, a detached entity has already been persisted, and I actually don't think that this is your real question. Now, if you want to know if an entity is new (i.e. doesn't have any persistent identity), what about this:

@Transient
public boolean isNew() {
    return (this.id == null);
}

这篇关于如何知道一个分离的 JPA 实体是否已经被持久化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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