2016-05-12 22 views
0

這裏的問題是我有:JPA:基於實例變量動態映射一個實體的表

class CurrencyPrice { 
    @Transient 
    String pair; 
    float spotPrice; 
    Date timeStamp; 
} 

而且我有3個表,該表的代表「歐元/英鎊的美元價值的姓名/日元分別「:usd_euro,usd_gbp & usd_yen。它們都有相同的3列:id,spotprice,timestamp。

出於某種原因,我不能有一張桌子。瞬態實例變量「對」將取決於它所代表以下值:「usd_euro」,「usd_gbp」 &「usd_yen」

  1. ,並根據在「對」的價值我想插入如果我在'pair'中有'usd_yen'的值,那麼這個對象應該保存在usd_yen表中。

  2. 而當我想取數據,我想JPA決定基於在「對」的值來選擇哪個表

這是簡單的JDBC,但有沒有辦法做到這在JPA?

謝謝。

+0

我碰到[this](http://stackoverflow.com/questions/3505866/how-to-map-one-class-to-different-tables-using-hibernate-jpa-annotations),然後引用到[this](http://stackoverflow.com/questions/997203/jpa-how-to-use-the-same-class-entity-to-map-different-tables)。看起來我不得不擁有多個實體類。 – kskblr07

回答

1

如果我正確理解你的要求,這實際上可能是JPA現在(你所引用的線程是很舊的)是可行的,如果你可以使用繼承你的實體額外的連接表,如果它是可以接受的每種類型的ID不是連續的。

你基本上可以定義類這樣便:

@Entity 
@Table(name="curr_base") // choose a suitable name 
@Inheritance(strategy=InheritanceType.JOINED) 
@DiscriminatorColumn(name="currency", discriminatorType=DiscriminatorType.STRING) // your join table needs this column in addition to the id 
public abstract class CurrencyPrice { 
    @Id 
    private int id; 
} 

@Entity 
@Table(name="usd_euro") 
@DiscriminatorValue("usd_euro") 
public class UsdEuroPrice extends CurrencyPrice { 
    float spotPrice; 
    Date timeStamp; 
} 

@Entity 
@Table(name="usd_gbp") 
@DiscriminatorValue("usd_euro") 
public class UsdGbpPrice extends CurrencyPrice { 
    float spotPrice; 
    Date timeStamp; 
} 

@Entity 
@Table(name="usd_yen") 
@DiscriminatorValue("usd_euro") 
public class UsdYenPrice extends CurrencyPrice { 
    float spotPrice; 
    Date timeStamp; 
} 

我對每個子類複製spotPricetimeStamp,這樣你就不必修改現有表定義 - 當然,這將是更清潔只有他們在超類/連接表上。

該映射允許它執行EntityManager.persist(new UsdGbpPrice(...))並讓JPA在右表中插入一行。欲瞭解更多信息,請看here

+0

嗨HeinBlöd,感謝您的詳細回覆。來到你答案的最後部分,是否有可能擁有GenericEntityManager.persist(CurrencyPrice)而不是UsdGbpPrice?試圖避免實體類型(貨幣對)特定的讀取/保留函數。事實上,NetBeans生成實體特定的JPA控制器 - 我正在嘗試使用通用的控制器。這將是很好,如果我能做到這一點:GenericEntityManager.persist(CurrencyPrice),它內部計算出應該堅持CurrencyPrice的表,而不必爲每個實體類型編寫/生成/維護代碼。 – kskblr07

+0

我還沒有嘗試過這個,但是在閱讀了一些線程之後(例如[this this])(http://stackoverflow.com/questions/8119678/jpa-entity-inheritance-with-abstract-classes-constrainviolationexception)),我相信它應該起作用。你顯然只需要在一個點上實例化一個具體的子類,然後你可以將它賦給一個用抽象超類型聲明的字段。該字段可以傳遞給您的GenericEntityManager。 –