MidnightLightning
MidnightLightning

Reputation: 6928

Check if a Hibernate PersistentBag is loaded?

I have a class that has a collection being fetched automatically, but in a lazy fashion, since it's not always needed. I have a method that relies on that that collection, but I want it to not trigger the lazy-loading if it hasn't fired already. Is there a way to tell if a PersistentBag has not been loaded, without triggering that load?

Example class:

class MyClass {
  private List<MyThings> toybox;

  @OneToMany (fetch = FetchType.LAZY, mappedBy = "toyBox")
  public List<MyThings> getToybox () {
    return toybox;
  }

  public void setToybox (List<MyThings> toybox) {
    this.toybox = toybox;
  }

  @Transient
  public List<String> toyNames() {
    if (hasNotAlreadyLoaded(this.toybox) {
      return null; // Can't run right now; data not available
    }
    return parseToybox(this.toybox);
  }
}

So, the question is what should boolean hasNotAlreadyLoaded(PersistantBag bag) do to check if the bag has been loaded? Checking the .size() I tried, but that triggers the load...

Upvotes: 2

Views: 3883

Answers (2)

Andy Dufresne
Andy Dufresne

Reputation: 6180

If you use JPA2 you can do it using PersistenceUnitUtil as below

PersistenceUnitUtil unitUtil = em.getEntityManagerFactory().getPersistenceUnitUtil();

Assert.assertTrue(unitUtil.isLoaded(myclassInstance));

Assert.assertFalse(unitUtil.isLoaded(myclassInstance, "toyBox"));

Upvotes: 1

Andr&#233;
Andr&#233;

Reputation: 2204

If you have access to the Hibernate API (Not pure JPA) you can use the method Hibernate.isInitialized(java.lang.Object)

From the Javadoc, it returns

true if the argument is already initialized, or is not a proxy or collection

Upvotes: 2

Related Questions