Hibernate中的Entity类之间的继承关系之一MappedSuperclass

时间:2022-09-07 14:49:30

在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