访问jpa实体的关系时出现NullPointerException

时间:2013-09-02 07:13:21

标签: java jpa java-ee-6

当我尝试为关系调用getter时,我得到一个空指针异常。我的理解是,容器将使用适当的列表对象填充此字段,同时仍然管理实体。

架构已预先存在,因此这是一个自下而上的映射。

这是我个人关系中的“一方”实体:

@Entity
@Table(name=CollectorHeader.TABLE_NAME)
public class CollectorHeader implements Serializable {
    ...
    @Id
    @Column(name = "COLLECTORHEADERID")
    private long id;

    @OneToMany(mappedBy="collectorHeader", fetch=FetchType.LAZY)
    private List<CollectorDetail> collectorDetails;
    ...
}

这是我的“多方”实体:

@Entity
@Table(name = CollectorDetail.TABLE_NAME)
public class CollectorDetail implements Serializable {
    ...
    @Id
    @Column(name = "COLLECTORDETAILID", unique = true)
    long id;
    ...
    @NotNull 
    @ManyToOne
    @JoinColumn(name = "COLLECTORHEADERID")
    private CollectorHeader collectorHeader;
    ...
    public CollectorDetail(long id, @NotNull CollectorHeader collectorHeader, 
                           long provenanceLinkPk, @NotNull String provenanceLinkClass) {
        setId(id);
        setCollectorHeader(collectorHeader);
        setProvenanceLinkPk(provenanceLinkPk);
        setProvenanceLinkClass(provenanceLinkClass);
    }
}

这就是我所说的关系:

public CollectorDetail createCollectorDetail(long collectorHeaderId, long     provenanceLinkPk, @NotNull String provenanceLinkClass) throws SystemException {
    CollectorHeader collectorHeader = em.find(CollectorHeader.class, collectorHeaderId);
    if(collectorHeader == null) {
        String error = "There is no Collector Header with the id: '" + collectorHeaderId + "'";
        log.error(error);
        throw new SystemException(error);
    }
    CollectorDetail collectorDetail =
        new CollectorDetail(NextNumberFactory.getInstance().getNextNumberLong("cocollectordetail")
                , collectorHeader
                , provenanceLinkPk
                , provenanceLinkClass);
    collectorHeader.getCollectorDetails().add(collectorDetail); //NULLPOINTEREXCEPTION
    em.merge(collectorDetail);
    em.merge(collectorHeader);
    return collectorDetail;
}

Sql Schema:

CREATE TABLE COCOLLECTORHEADER (
    COLLECTORHEADERID   DECIMAL(20,0) NOT NULL PRIMARY KEY,
    COLLECTEDTIMESTAMP TIMESTAMP, -- the date when the information was collected
    PROCESSEDTIMESTAMP TIMESTAMP, -- the date when the information was processed
    FILEFORMAT VARCHAR(16) NOT NULL,
    SEQUENCENUMBER INTEGER
);

CREATE TABLE COCOLLECTORDETAIL (
    COLLECTORDETAILID   DECIMAL(20,0) NOT NULL PRIMARY KEY,
    COLLECTORHEADERID   DECIMAL(20,0) NOT NULL
        REFERENCES COCOLLECTORHEADER(COLLECTORHEADERID),
    PROVENANCELINKPK        DECIMAL(20,0) NOT NULL,
    PROVENANCELINKCLASS VARCHAR(128) NOT NULL
);

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

使用有效的集合对象初始化collectorDetails

private List<CollectorDetail> collectorDetails = new ArrayList<CollectorDetail>();

同时检查Is it good practice to initialize fields inside a JPA entity getter?