java - OneToMany 关系不起作用

标签 java jpa entity one-to-many

我的表:

产品:ID、名称

Offer:id、value、product_id

实体:

@Entity
@Table(name="product")
public class Product implements Serializable {
    @OneToMany(mappedBy="product")
    private Set<Offer> offers;
    ...
}

@Entity
@Table(name="offer")
public class Offer implements Serializable {
    @ManyToOne
    @JoinColumn(name="PRODUCT_ID")
    private Product product;
    ...
}

当我尝试从表 Product 中获取一些数据时,我得到一个 java.lang.NullPointerException,并且这个代码:product.getOffers() 返回:

{IndirectSet: not instantiated}

如何解决这个问题?

最佳答案

不是错误消息。打印指令导致在底层 IndirectSet 上调用 toString() .

TopLink will place an IndirectSet in the instance variable when the containing domain object is read from the datatabase. With the first message sent to the IndirectSet, the contents are fetched from the database and normal Set behavior is resumed.

IndirectCollection类型被具体实现为不在 toString() 上实例化:

For debugging purposes, #toString() will not trigger a database read.

但是,对间接集合的任何其他调用,例如 size() 或 isEmpty() 都会实例化该对象。

The database read is ultimately triggered when one of the "delegated" methods makes the first call to getDelegate(), which in turn calls buildDelegate(), which sends the message getValue() to the value holder. The value holder performs the database read. With the first message sent to the IndirectSet, the contents are fetched from the database and normal Set behavior is resumed.

另见 IndirectList: not instantiated

关于java - OneToMany 关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8301820/

相关文章:

java - 无法分配给manifest.xml中的android.app.activity

java - 无法创建 sessionFactory object.org.hibernate.InvalidMappingException : Could not parse mapping document from resource Employee. hbm.xml

java - 使用 JPA 在 GAE 中保存许多实体

php - [Symfony2]Catchable Fatal Error : Object of class [. ..] 无法转换为字符串

java - "Could not find a suitable constructor"使用 Jersey 2 从我的资源类中提取接口(interface)时

java - JSF (PrimeFaces) 页面不适用于单一表单

java - 从一个类到另一个类使用 JTextField

java - 在 JPA 或 Hibernate 查询中使用 Constructor Result 会影响性能吗?

java - 如何使用 JsonManagedReference 从相关对象读取属性

java - Morphia 在从实体子类更新字段时更改 className