天天看点

Hibernate中的Entity类之间的继承关系之三JOINED

对于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 )
)
           

继续阅读