【问题标题】:How to know if an EclipseLink entity is detached?如何知道 EclipseLink 实体是否已分离?
【发布时间】:2011-01-05 14:57:30
【问题描述】:

您知道任何了解 JPA 实体状态的方法吗?我遇到了一些错误,我需要知道实体是分离的还是托管的。

我正在使用 EclipseLink 2.1.2

【问题讨论】:

    标签: jpa eclipselink


    【解决方案1】:

    EntityManager.contains()

    检查实例是否是属于当前持久性上下文的托管实体实例。

    【讨论】:

    • 如果对象由不同的 EntityManager 管理?它返回 false ... 这并不意味着它已分离。
    • This SO post 讨论了为什么@DataNucleus 是正确的。
    【解决方案2】:

    前面的答案部分正确。

    您必须检查其他州以获得更高的置信度。

    我使用以下代码,其中我有自己的托管 EntityManager / EntityManagerFactory。

    /**
     * Check if an entity is detached or not
     * @param entity
     * @return true, if the entity is managed
     */
     public boolean isDetached(AbstractEntity entity) {
            // pick the correct EntityManager, somehow
            EntityManager em = getMyEntityManager(entity);
            try {
                if (em == null)
                    return false;
    
                return entity.getID() != null // must not be transient
                        && !em.contains(entity) // must not be managed now
                        && em.find(Entity.class, entity.getID()) != null; // must not have been removed
            } finally {
                if (em != null)
                    em.close();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 2012-11-08
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多