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

查看:29
本文介绍了如何测试延迟加载的 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.

当然,如果客户端从未接触过该集合,我的服务就不必检查它是否有可能发生的变化.问题是我似乎无法找到一种方法来测试集合是否已初始化.我想我可以在它上面调用 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 吗?

Are you using JPA2?

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

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

例如组织和用户之间存在双向的一对多/多对一关系.

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天全站免登陆