How to know if a detached JPA entity has already been persisted or not?

后端 未结 1 1625
悲&欢浪女
悲&欢浪女 2020-12-12 21:37

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 prese

相关标签:
1条回答
  • 2020-12-12 22:25

    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):

    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.

    And a graphical illustration:

    alt text

    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);
    }
    
    0 讨论(0)
提交回复
热议问题