OpenJPA无法获取OneToOne关系

时间:2013-02-03 08:57:40

标签: jpa openjpa

我正在使用OpenJPA 2.2.1并遇到以下问题:

TypedQuery<OdpObjectScheduleEntity> q = em.createQuery(
    "SELECT s FROM OdpObjectScheduleEntity s WHERE s.updateFreq IS NOT NULL",
    OdpObjectScheduleEntity.class);
List<OdpObjectScheduleEntity> result = q.getResultList();

这是OdpObjectScheduleEntity

package ru.focusmedia.odp.server.datastore.jpa.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import ru.focusmedia.odp.server.datastore.api.objects.OdpObjectScheduleRecord;

@Entity
@Table(name = "object_schedules")
public class OdpObjectScheduleEntity implements OdpObjectScheduleRecord {
    // fetch=FetchType.EAGER is the default. 
    // I've also tried explicitly setting it, no difference.
    @OneToOne(optional = false) 
    @Column(nullable = false)
    @Id
    private OdpObjectEntity object;

    @Column(name = "update_freq_seconds", nullable = true)
    private Integer updateFreq;

    protected OdpObjectScheduleEntity() {
        // for JPA
    }

    public OdpObjectScheduleEntity(OdpObjectEntity object, Integer updateFreq) {
        this.object = object;
        this.updateFreq = updateFreq;
    }

    @Override
    public OdpObjectEntity getObject() {
        return object;
    }

    @Override
    public Integer getUpdateFreq() {
        return updateFreq;
    }

    public void setUpdateFreq(Integer updateFreq) {
        this.updateFreq = updateFreq;
    }

    @Override
    public String toString() {
        return "OdpObjectScheduleEntity [object=" + object + ", updateFreq="
                + updateFreq + "]";
    }
}

但是result的元素看起来好像是懒惰地取出对象,例如OdpObjectScheduleEntity [object=OdpObjectEntity [id=23851, name=null, parent=null, odpClass=null], updateFreq=120]。我错过了一些明显的东西,或者这是OpenJPA中的一个错误?我可以通过做一些像

这样糟糕的事情来解决这个问题
for (OdpObjectScheduleEntity schedule : result) {
    // simply schedule.getObject() doesn't work
    schedule.getObject().toString();
}

有没有更好的方法强制加载关系?

1 个答案:

答案 0 :(得分:1)

我从未使用过OpenJPA,因此我无法告诉您哪些是错误的,但您可以尝试使用JOIN FETCH

TypedQuery<OdpObjectScheduleEntity> q = em.createQuery(
    "SELECT s FROM OdpObjectScheduleEntity s LEFT JOIN FETCH s.object WHERE s.updateFreq IS NOT NULL",
    OdpObjectScheduleEntity.class);
List<OdpObjectScheduleEntity> result = q.getResultList();

有关详细信息,请参阅示例http://docs.oracle.com/html/E24396_01/ejb3_langref.html#ejb3_langref_fetch_joins