OneToMany relationship is not working

余生长醉 提交于 2019-11-30 12:15:47

问题


My Tables:

Product: id, name

Offer: id, value, product_id

Entities:

@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;
    ...
}

When I try to get some data from table Product, I get a java.lang.NullPointerException, and this code: product.getOffers() returns:

{IndirectSet: not instantiated}

How to fix this?


回答1:


This not an error message. The print instruction results in toString() being invoked on the underlying IndirectSet.

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 types are specifically implemented not to instantiate on toString():

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

However, any other call on the indirect collection, e.g., size() or isEmpty() will instantiate the object.

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.

See also IndirectList: not instantiated




回答2:


If you get {IndirectSet: not instantiated} when accessing product.getOffers() than most probably you're executing this code outside of the transaction.

By default @OneToMany and @ManyToMany relationships are lazy loaded which means that, for better performance, you'll get data fetched only when you want to access it for the first time. This must happen within an active transaction.
If you don't access this data within this scope than you cannot access this data no more. You should either put your invocation code within the active transaction or change the collection to be eager instead of lazy:

@OneToMany(mappedBy="product", fetch=FetchType.EAGER)



回答3:


Here's what I did

// force load of the set.
entity.getSecrets().isEmpty();
System.out.println(entity.getSecrets());



回答4:


This solved my issue

@OneToMany(mappedBy = "columnName", cascade = { CascadeType.ALL}, fetch=FetchType.EAGER)



来源:https://stackoverflow.com/questions/8301820/onetomany-relationship-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!