JPA没有加载延迟获取集合的问题

时间:2012-04-19 20:17:19

标签: java sql-server-2008 jpa websphere

我遇到了JPA拒绝获取设置为获取延迟的集合的问题。以下是实体的定义方式:

报告实体

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

主机实体

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

由于某种原因,我无法将主机设置为加载到内存中,并且主机始终为空。我在stackoverflow帖子上找到了以下内容,但它也不起作用:

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();
}

以上输出:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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