2

I'm having a problem with JPA refusing to fetch a collection that is set to fetch lazy. Here are how the entities are defined:

Report Entity

//bi-directional many-to-one association to Host
@OneToMany(mappedBy="report", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Set<Host> hosts;

Host Entity

//bi-directional many-to-one association to Report
@ManyToOne
@JoinColumn(name="INCIDENT_ID")
private Report report;

For some reason I can't get the hosts set to load into memory and hosts is always null. I found the following on a stackoverflow post, but it doesn't work either:

public void loadHosts(Report report)
{
    PersistenceUtil unitUtil = getEntityManager().getEntityManagerFactory().getPersistenceUnitUtil();
    System.out.println("isLoaded(report, \"hosts\"): " + unitUtil.isLoaded(report, "hosts"));
    initializeCollection(report.getHosts());
    System.out.println("isLoaded(report, \"hosts\"): " + unitUtil.isLoaded(report, "hosts"));
}

private void initializeCollection(Collection<?> collection) 
{
    if(collection == null) 
    {
        return;
    }
    collection.iterator().hasNext();
}

Output from the above:

SystemOut     O isLoaded(report, "hosts"): false
SystemOut     O isLoaded(report, "hosts"): false

Any ideas?

4

1 回答 1

0

我认为您必须在 session.get(object) 和 tx.commit 之间调用 getHosts。或者您也可以决定使用 fetch=FetchType.EAGER (尽管这可能不是一个好主意)

于 2012-04-19T20:19:55.587 回答