簡體   English   中英

@ElementCollection with Map <Entity, Embeddable> 其中Entity是Embeddable的一個字段

[英]@ElementCollection with Map<Entity, Embeddable> where Entity is a field of the Embeddable

在搜索了JPA文檔和各種帖子之后,我對使用JPA2.0是否可以實現以下內容感到困惑。 我剛剛開始使用JPA,請原諒我,如果我做了一些愚蠢的事,

我的域模型有一個“投資組合”,其中包含零個或多個“未平倉頭寸”。 職位由“工具”(JPA實體)和價格(雙重)組成。 投資組合如下:

@Entity (name = "portfolio")
public class Portfolio {
    @Id
    @Column (name = "id")
    @GeneratedValue
    private long id;

    @ElementCollection (fetch = FetchType.EAGER)
    @CollectionTable (name = "portfolio_entry", joinColumns = @JoinColumn (name = "portfolio_id"))
    private final Map<Instrument, OpenPosition> positions = new HashMap<Instrument, OpenPosition>();
....

OpenPosition Embeddable如下:

@Embeddable
public class OpenPosition extends Position {
    @ManyToOne (targetEntity = InstrumentImpl.class, optional = false)
    @JoinColumn (name = "instrument_id", nullable = false)
    protected Instrument instrument;

    @Column (name = "price", nullable = false)
    protected double price;
....

儀器實體是:

@Entity (name="instrument")
public class Instrument {
    @Id
    @Column(name = "id")
    @GeneratedValue
    private long id;

    @Column(name = "isin", nullable = false)
    private String isin;
....    
    @Override 
    public int hashCode() {
        int hash = 17;
        hash = 31 * hash + isin.hashCode();
    ....

當我嘗試使用它時,創建了模式並且我能夠持久化組合,但是當嘗試檢索它們時,我在Instrument類的hashCode方法中得到NullPointerException。 似乎JPA試圖獲取哈希碼來構建Map鍵,但Instrument對象尚未加載。

我可以看到調試雖然id在Instrument對象中設置,但所有其他字段都為null。

所以我的問題是,JPA2.0是否允許ElementCollection,其中鍵是一個Entity,它也作為Embeddable值的字段存在? 如果是這樣,我搞砸了什么。 如果沒有,是使用Instrument實體的id作為密鑰的最佳解決方法嗎?

提前致謝。

ps我正在使用hibernate 4.1.4 JPA實現。

所以我的問題是,JPA2.0是否允許ElementCollection,其中鍵是一個Entity,它也作為Embeddable值的字段存在?

是的,我設法用這個映射做到了:

@ElementCollection( targetClass = FreightBid.class )
@MapKeyJoinColumn( name = "carrier_id", referencedColumnName = "id" )
@CollectionTable( name = "freight_bid",
    joinColumns = @JoinColumn( name = "offer_pool_id" ) )
@Access( AccessType.FIELD )
private Map<Carrier,FreightBid> bidsByCarrier;

就我而言,Carrier是@Entity而FreightBid是@Embedded

我已經能夠持久存儲並正確檢索包含此地圖的實體。

我搞砸了什么

您應該移除受現場protected Instrument instrument; 來自OpenPosition類,而是使用Portfolio類中的map字段上的注釋@MapKeyJoinColumn來聲明哪個列應該用作映射鍵的連接列。

另外,最好避免在對象的hashCode方法中使用除id之外的其他字段作為映射鍵... JPA實現者可能會搞砸了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM