Hibernate中的Entity类之间的继承关系之三JOINED
2016-06-07 22:46
281 查看
对于Hibernate提供的4种兼容JPA的映射策略,这里介绍第三种Joined table,也被称为table-per-subclass策略。
在这种策略中,存在如下特征:
父子Entity类都对应各自的数据库表
父表中无需设置discriminator列
子表中的主键ID,也是子表的外键,用以指向父表的主键ID。默认父子表中的主键名字相同,也可以在子Entity类中通过如下标注给出列名。
访问子Entity类时需要在数据库中join访问父Entity类
父Entity类定义如下:
子Entity类定义如下:
另一个子Entity类定义如下:
数据库表结构如下:
在这种策略中,存在如下特征:
父子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 ) )
相关文章推荐
- PostgreSQL教程(三):表的继承和分区表详解
- Lua面向对象之类和继承浅析
- 浅析Ruby中继承和消息的相关知识
- C# Entity Framework中的IQueryable和IQueryProvider详解
- 设计引导--一个鸭子游戏引发的设计理念(多态,继承,抽象,接口,策略者模式)
- C++实现不能被继承的类实例分析
- C# 面向对象三大特性:封装、继承、多态
- PHP类的封装与继承详解
- 使用Entity Framework(4.3.1版本)遇到的问题整理
- js继承 Base类的源码解析
- Javascript 面向对象 继承
- JavaScript 继承使用分析
- Javascript面向对象编程(二) 构造函数的继承
- Javascript中的几种继承方式对比分析
- javascript面向对象之Javascript 继承
- JavaScript 对象、函数和继承
- 详述JavaScript实现继承的几种方式(推荐)
- javascript 继承学习心得总结
- 学习javascript面向对象 javascript实现继承的方式
- 关于JavaScript的面向对象和继承有利新手学习