jpa-table列引用作为两个不同表的外键

yvfmudvl  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(293)

各位开发人员:,
我目前的情况:我使用的是jpa2.1,在一个表中,我有一列在外键关系中引用了两个不同的表。
如何在jpa中描述这一点?

Table Book 
  taxRateId (manyToOne) (GermanTax/AustrianTax)
  countryType

Table GermanTax
  taxRateId (oneToMany Books)

Table AustrianTax
  taxRateId (oneToMany Books)

CONSTRAINT germanTax FOREIGN KEY (tax_rate_id) REFERENCES german_tax (id)

CONSTRAINT austrianTax FOREIGN KEY (tax_rate_id) REFERENCES austrian_tax (id),
lf3rwulv

lf3rwulv1#

我想到了这种Map方法:

@Entity 
@Inheritance(InheritanceType.TABLE_PER_CLASS)
public abstract class Tax {
    @Id
    @Column(name = "taxRateId")
    //@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk-sequence")
    //@SequenceGenerator(name = "pk-sequence", sequenceName = "ID_GEN", allocationSize = 1)
    protected Long taxRateId = -1;

    public long getTaxRateId() {
        return taxRateId;
    } 

    @Column(nullable=false)
    private double taxRate;

    @Column(nullable=false)
    private String countryName; // countryType ?

    // getters and setters for 'taxRate' and `countryName`
}

接下来,我们定义两个具体的税务实体,如下所示:

@Entity
public class AustrianTax extends Tax {
    // nothing special here, the type differentiates enough
}

@Entity
public class GermanTax extends Tax {
    // nothing special here, see above --^
}

然后,我们绘制Map Book 以一种通用的方式 Tax ```
/*

  • As you brought up the question
    */
    @Entity
    public class Book {
    // fields & annotations for ID attribute and generation strategy, similar to above

    @OneToMany
    private Set countryRates;

    // getters and setters, add and remove for 'countryRates'
    }

但是,将其定义为以下内容将更精确,并且符合3nf中的数据模型:

/*

  • One book can refer to 1 or more rates (Austrian/German) AND

  • One rate can be applied to 1 or more books -> @ManyToMany
    */
    @Entity
    public class Book {
    // fields & annotations for ID attribute and generation strategy, similar to above

    @ManyToMany
    private Set countryRates;

    // getters and setters, add and remove for 'countryRates'
    }

后一种情况的一般假设/理由( `@ManyToMany` ): 
某一本书(同一本书)在不同的国家出售,这些国家提高了不同的税率。因此,如果可以的话,我的建议是更改数据库模式(表结构)。这将产生一个Map关系的n:m表 `|Book| 0..* <--> 0..* |Tax|` 正确的(在语义上)。脚注:我希望你还处在发展的初级阶段。
只剩下属性了 `countryType` 我无法将其关联为类型的属性 `Book` 假设一本书没有被修改为奥地利方言,因此印刷了不同的内容(这里说的是德语;-))。然而,对于大多数d-a-ch书籍来说,这并不是一个常见的情况。
希望这有帮助。

相关问题