How to test whether lazy loaded JPA collection is initialized?

前端 未结 3 1725
时光说笑
时光说笑 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 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();
    }
    

提交回复
热议问题