How to test whether lazy loaded JPA collection is initialized?

前端 未结 3 1723
时光说笑
时光说笑 2020-12-04 21:05

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

相关标签:
3条回答
  • 2020-12-04 21:47
    org.hibernate.Hibernate.isInitialized(..)
    

    There is no standard JPA solution to my knowledge. But if you want to actually initialize collections, you can create an utility method and iterate them (only one iteration is enough).

    0 讨论(0)
  • 2020-12-04 21:58

    For eclipselink, users cast the collection you are trying to access to an org.eclipse.persistence.indirection.IndirectList, and then call its isInstantiated() method. The following link has more information:

    http://www.eclipse.org/eclipselink/api/1.1/org/eclipse/persistence/indirection/IndirectList.html#isInstantiated.

    0 讨论(0)
  • 2020-12-04 22:04

    Are you using JPA2?

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