1. 程式人生 > >Hibernate中的Entity類之間的繼承關系之一MappedSuperclass

Hibernate中的Entity類之間的繼承關系之一MappedSuperclass

兼容 target static sql tac java 數據 har not

在hibernate中,Entity類可以繼承Entity類或非Entity類。但是,關系數據庫表之間不存在繼承的關系。那麽在Entity類之間的繼承關系,在數據庫表中如何表示呢?

Hibernate提供了4種兼容JPA的策略,解決Entity類的繼承與關系數據庫表的對應不匹配問題。這裏介紹第一種MappedSuperclass。

在這種策略中,存在如下特征:

只在Entity類之間存在繼承關系,其中的父Entity類使用@javax.persistence.MappedSuperclass標註。

在關系數據庫中沒有父Entity類,一個具體子Entity類對應一個表,其中包含一個具體子Entity類的全部屬性(包含父Entity類的屬性)。

示例中,父Entity類定義如下:

@MappedSuperclass
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")
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")
public static class CreditAccount extends Account {

    private BigDecimal creditLimit;

    public BigDecimal getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(BigDecimal creditLimit) {
        this.creditLimit = creditLimit;
    }
}

  

數據庫表結構如下:

CREATE TABLE DebitAccount (  
    id BIGINT NOT NULL ,  
    balance NUMERIC(19, 2) ,  
    interestRate NUMERIC(19, 2) ,  
    owner VARCHAR(255) ,  
    overdraftFee NUMERIC(19, 2) ,  
    PRIMARY KEY ( id )  
)  
  
CREATE TABLE CreditAccount (  
    id BIGINT NOT NULL ,  
    balance NUMERIC(19, 2) ,  
    interestRate NUMERIC(19, 2) ,  
    owner VARCHAR(255) ,  
    creditLimit NUMERIC(19, 2) ,  
    PRIMARY KEY ( id )  
)  

  

via:http://blog.csdn.net/taiyangdao/article/details/51578386

Hibernate中的Entity類之間的繼承關系之一MappedSuperclass