如何测试延迟加载的JPA集合是否已初始化? [英] How to test whether lazy loaded JPA collection is initialized?

查看:223
本文介绍了如何测试延迟加载的JPA集合是否已初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从外部代码获取JPA实体的服务。在这个服务中,我想遍历一个延迟加载的集合,该集合是该实体的一个属性,以查看客户端相对于数据库中的当前版本是否添加了某些内容。

I have a service that gets a JPA entity from outside code. In this service I would like to iterate over a lazily loaded collection that is an attribute of this entity to see if the client has added something to it relative to the current version in the DB.

然而,客户端可能从来没有碰过这个集合,所以它还没有初始化。这导致众所周知的

However, the client may have never touched the collection so it's still not initialized. This results in the well known

org.hibernate.LazyInitializationException:无法懒惰地初始化一个角色集合:com.example.SomeEntity。 code>

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.SomeEntity.

当然,如果客户端永远不会触及集合,我的服务不必检查它是否可能发生更改。问题是,我似乎无法找到一种方法来测试集合是否已初始化。我想我可以对它调用 size(),如果它抛出 LazyInitializationException 我就会知道,但我正在尝试不要依赖这种模式。

Of course, if the client never touched the collection, my service doesn't have to check it for possible changes. The thing is that I can't seem to find a way to test whether the collection is initialized or not. I guess I could call size() on it and if it throws LazyInitializationException I would know, but I'm trying not to depend on such patterns.

是否有某些 isInitialized()方法?

推荐答案

您是否使用JPA2?

PersistenceUnitUtil 有两个方法可用于确定实体的加载状态。

PersistenceUnitUtil has two methods that can be used to determine the load state of an entity.

例如在组织和用户之间有一个双向OneToMany / ManyToOne关系。

e.g. there is a bidirectional OneToMany/ManyToOne relationship between Organization and User.

public void test() {
    EntityManager em = entityManagerFactory.createEntityManager();
    PersistenceUnitUtil unitUtil =
        em.getEntityManagerFactory().getPersistenceUnitUtil();

    em.getTransaction().begin();
    Organization org = em.find(Organization.class, 1);
    em.getTransaction().commit();

    Assert.assertTrue(unitUtil.isLoaded(org));
    // users is a field (Set of User) defined in Organization entity
    Assert.assertFalse(unitUtil.isLoaded(org, "users"));

    initializeCollection(org.getUsers());
    Assert.assertTrue(unitUtil.isLoaded(org, "users"));
    for(User user : org.getUsers()) {
        Assert.assertTrue(unitUtil.isLoaded(user));
        Assert.assertTrue(unitUtil.isLoaded(user.getOrganization()));
    }
}

private void initializeCollection(Collection<?> collection) {
    // works with Hibernate EM 3.6.1-SNAPSHOT
    if(collection == null) {
        return;
    }
    collection.iterator().hasNext();
}

这篇关于如何测试延迟加载的JPA集合是否已初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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