對于Hibernate提供的4種相容JPA的映射政策,這裡介紹第三種Joined table,也被稱為table-per-subclass政策。
在這種政策中,存在如下特征:
- 父子Entity類都對應各自的資料庫表
- 父表中無需設定discriminator列
- 子表中的主鍵ID,也是子表的外鍵,用以指向父表的主鍵ID。預設父子表中的主鍵名字相同,也可以在子Entity類中通過如下标注給出列名。
@javax.persistence.PrimaryKeyJoinColumn(name="CUST_ID")
- 通路子Entity類時需要在資料庫中join通路父Entity類
父Entity類定義如下:
@Entity(name = "Account")
@javax.persistence.Inheritance(strategy = InheritanceType.JOINED)
public static class Account {
@Id
private Long id;
private String owner;
private BigDecimal balance;
private BigDecimal interestRate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public BigDecimal getInterestRate() {
return interestRate;
}
public void setInterestRate(BigDecimal interestRate) {
this.interestRate = interestRate;
}
}
子 Entity類定義如下:
@Entity(name = "DebitAccount")
@javax.persistence.PrimaryKeyJoinColumn(name = "account_id")
public static class DebitAccount extends Account {
private BigDecimal overdraftFee;
public BigDecimal getOverdraftFee() {
return overdraftFee;
}
public void setOverdraftFee(BigDecimal overdraftFee) {
this.overdraftFee = overdraftFee;
}
}
另一個子Entity類定義如下:
@Entity(name = "CreditAccount")
@javax.persistence.PrimaryKeyJoinColumn(name = "account_id")
public static class CreditAccount extends Account {
private BigDecimal creditLimit;
public BigDecimal getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(BigDecimal creditLimit) {
this.creditLimit = creditLimit;
}
}
資料庫表結構如下:
CREATE TABLE Account (
id BIGINT NOT NULL ,
balance NUMERIC(19, 2) ,
interestRate NUMERIC(19, 2) ,
owner VARCHAR(255) ,
PRIMARY KEY ( id )
)
CREATE TABLE CreditAccount (
creditLimit NUMERIC(19, 2) ,
account_id BIGINT NOT NULL REFERENCES Account(id),
PRIMARY KEY ( id )
)
CREATE TABLE DebitAccount (
overdraftFee NUMERIC(19, 2) ,
account_id BIGINT NOT NULL REFERENCES Account(id),
PRIMARY KEY ( id )
)