有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaJPA:基于实例变量将实体动态映射到表

我的问题是:

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

我有三个表,分别代表“欧元/英镑/日元的美元价值”:美元欧元、美元英镑和日元;美元/日元。它们都有相同的3列:id、spotprice、timestamp

由于某种原因,我不能有一张桌子。瞬态实例变量“pair”将根据其表示的内容具有以下值:“usd_euro”、“usd_gbp”&;“美元/日元”

  1. 根据‘pair’中的值,我想在其中一个表中插入一行,例如:如果‘pair’中的值为“usd_yen”,那么该对象应该保存在usd_yen表中

  2. 当我想要获取数据时,我希望JPA根据“pair”中的值来决定从哪个表中进行选择。

这在JDBC中很简单,但在JPA中有没有实现这一点的方法

多谢各位


共 (1) 个答案

  1. # 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