mysql - JPA -表列引用作为两个不同表的外键

标签 mysql jpa foreign-keys one-to-many many-to-one

亲爱的开发者您好,

我目前的情况:我正在使用 JPA 2.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),

最佳答案

我想出了这种映射方法:

@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`
}

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

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

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

然后,我们映射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<Tax> 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<Tax> countryRates;

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

后一种情况的一般假设/基本原理(@ManyToMany):

某本书(同一本书)在不同的国家/地区销售,税率不同。因此,我的建议是如果可以的话更改数据库模式(表结构)。这将产生一个n:m表来映射关系

|Book| 0..* <--> 0..* |Tax|

正确(在语义意义上)。脚注:我希望您仍处于开发的早期阶段。

唯一剩下的就是属性 countryType我无法将其关联为 Book 类型的属性假设一本书没有针对奥地利方言进行修改,因此印有不同的内容(这里以德国人的身份说话;-))。然而,对于大多数 D-A-CH 书籍来说,这种情况并不常见。

希望这有帮助。

关于mysql - JPA -表列引用作为两个不同表的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49779045/

相关文章:

java - 为什么 EntityManager 关闭了?

java - jpql (JPA) 中重复的父子数据

验证错误: Value is not valid

mysql - 添加外键时遇到问题

mysql - 在 MySQL 中使用内连接可以实现这一点吗?

php - 使用复选框和 AJAX 添加到 mysql

MySQL - group_concat 拉入额外的错误数据

django - 在 ListView 中使用外键值过滤查询集

django - Django : exactly 1 of 2 foreign keys has to be null 中的约束

mysql - SQL 查询中的列计数