一、结构

You can map an entire class hierarchy to a single table. This table includes columns for all properties of all classes in the hierarchy. The value of an extra type discriminator column or formula identifies the concrete subclass represented by a particular row. Figure 6.2 shows this approach.

二、代码

1.

 package org.jpwh.model.inheritance.singletable;

 import org.jpwh.model.Constants;

 import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.validation.constraints.NotNull; @Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "BD_TYPE")
public abstract class BillingDetails { @Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; @NotNull // Ignored by Hibernate for schema generation!
@Column(nullable = false)
protected String owner; // ... protected BillingDetails() {
} protected BillingDetails(String owner) {
this.owner = owner;
} public Long getId() {
return id;
} public String getOwner() {
return owner;
} public void setOwner(String owner) {
this.owner = owner;
}
}

2.

 package org.jpwh.model.inheritance.singletable;

 import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull; @Entity
@DiscriminatorValue("BA")
public class BankAccount extends BillingDetails { @NotNull
protected String account; @NotNull
protected String bankName; @NotNull
protected String swift; public BankAccount() {
super();
} public BankAccount(String owner, String account, String bankName, String swift) {
super(owner);
this.account = account;
this.bankName = bankName;
this.swift = swift;
} public String getAccount() {
return account;
} public void setAccount(String account) {
this.account = account;
} public String getBankName() {
return bankName;
} public void setBankName(String bankName) {
this.bankName = bankName;
} public String getSwift() {
return swift;
} public void setSwift(String swift) {
this.swift = swift;
}
}

3.

 package org.jpwh.model.inheritance.singletable;

 import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull; @Entity
@DiscriminatorValue("CC")
public class CreditCard extends BillingDetails { @NotNull // Ignored by Hibernate for DDL generation!
protected String cardNumber; @NotNull
protected String expMonth; @NotNull
protected String expYear; // ... public CreditCard() {
super();
} public CreditCard(String owner, String cardNumber, String expMonth, String expYear) {
super(owner);
this.cardNumber = cardNumber;
this.expMonth = expMonth;
this.expYear = expYear;
} public String getCardNumber() {
return cardNumber;
} public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
} public String getExpMonth() {
return expMonth;
} public void setExpMonth(String expMonth) {
this.expMonth = expMonth;
} public String getExpYear() {
return expYear;
} public void setExpYear(String expYear) {
this.expYear = expYear;
}
}

4.在无法改变表结构增加discriminator的情况下,可以使用Hibernate的扩展注解@DiscriminatorFormula,底层是利用数据库的case when 语句

 package org.jpwh.model.inheritance.singletableformula;

 import org.jpwh.model.Constants;

 import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.validation.constraints.NotNull; @Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@org.hibernate.annotations.DiscriminatorFormula(
"case when CARDNUMBER is not null then 'CC' else 'BA' end"
)
public abstract class BillingDetails {
// ...
@Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; @NotNull
protected String owner; protected BillingDetails() {
} protected BillingDetails(String owner) {
this.owner = owner;
} public Long getId() {
return id;
} public String getOwner() {
return owner;
} public void setOwner(String owner) {
this.owner = owner;
}
}

三、SINGLE_TABLE的优缺点

1.优点

(1)This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and non-polymorphic queries perform well—and it’s even easy to write queries by hand. Ad hoc reporting is possible without complex joins or unions. Schema evolution is straightforward.

Hibernate generates the following  SQL for  select bd from BillingDetails bd :

 select
ID, OWNER, EXPMONTH, EXPYEAR, CARDNUMBER,
ACCOUNT, BANKNAME, SWIFT, BD_TYPE
from
BILLINGDETAILS

To query the CreditCard subclass, Hibernate adds a restriction on the discriminator column:

 select
ID, OWNER, EXPMONTH, EXPYEAR, CARDNUMBER
from
BILLINGDETAILS
where
BD_TYPE='CC'

2.缺点

(1)the loss of NOT NULL constraints may be a serious problem from the point of view of data correctness. Imagine that an expiration date for credit cards is required, but your database schema can’t enforce this rule because all columns of the table can be NULL .

(2)Another important issue is normalization. You’ve created functional dependencies between non-key columns, violating the third normal form. As always, denormalization for performance reasons can be misleading, because it sacrifices long-term stability,maintainability, and the integrity of data for immediate gains that may be also achieved
by proper optimization of the SQL execution plans (in other words, ask your DBA ).

(3)considering denormalized schemas can become a major burden in the long term. Your DBA may not like it at all

(4)An implementation quirk of Hibernate requires that you declare nullability with @Column because Hibernate
ignores Bean Validation’s @NotNull when it generates the database schema.Hibernate ignores the @NotNull for schema DDL generation, but it observes it at runtime, before inserting a row.

JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-004Table per class hierarchy(@Inheritance..SINGLE_TABLE)、@DiscriminatorColumn、@DiscriminatorValue、@DiscriminatorFormula)的更多相关文章

  1. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-005Table per subclass with joins(@Inheritance(strategy = InheritanceType.JOINED)、@PrimaryKeyJoinColumn、)

    一.结构 The fourth option is to represent inheritance relationships as SQL foreign key associations. Ev ...

  2. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-008Polymorphic many-to-one associations(@ManyToOne、@Inheritance、)

    一.结构 二.代码 1. package org.jpwh.model.inheritance.associations.manytoone; import org.jpwh.model.Consta ...

  3. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-006Mixing inheritance strategies(@SecondaryTable、@PrimaryKeyJoinColumn、<join fetch="select">)

    一.结构 For example, you can map a class hierarchy to a single table, but, for a particular subclass, s ...

  4. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-003Table per concrete class with unions(@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)、<union-subclass>)

    一.代码 1. package org.jpwh.model.inheritance.tableperclass; import org.jpwh.model.Constants; import ja ...

  5. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-002Table per concrete class with implicit polymorphism(@MappedSuperclass、@AttributeOverride)

    一.结构 二.代码 1. package org.jpwh.model.inheritance.mappedsuperclass; import javax.persistence.MappedSup ...

  6. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-001Hibernate映射继承的方法

    There are four different strategies for representing an inheritance hierarchy: Use one table per co ...

  7. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-009Polymorphic collections(@OneToMany(mappedBy = "user")、@ManyToOne、)

    一.代码 1. package org.jpwh.model.inheritance.associations.onetomany; import org.jpwh.model.Constants; ...

  8. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-007Inheritance of embeddable classes(@MappedSuperclass、@Embeddable、@AttributeOverrides、、)

    一.结构 二.代码 1. package org.jpwh.model.inheritance.embeddable; import javax.persistence.MappedSuperclas ...

  9. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-007UserTypes的用法(@org.hibernate.annotations.Type、@org.hibernate.annotations.TypeDefs、CompositeUserType、DynamicParameterizedType、、、)

    一.结构 二.Hibernate支持的UserTypes接口  UserType —You can transform values by interacting with the plain JD ...

随机推荐

  1. java_报表_00_资源帖

    一.精选资料 二.java api 1.jfreechart (1).Java-jfree报表(学习整理)----饼状图.柱状图.折线统计图 (2).Jfreechart打造专业图表-原来Jfreec ...

  2. mysql数据库乱码问题

    设置如下:SET character_set_client=utf8; SET character_set_results=utf8; SET character_set_connection=utf ...

  3. 基于zepto移动4*3九宫格转奖

    最近根据公司需求,要把移动端的圆形转盘抽奖,改为九宫格的形式,查找资料搞定了,纪录下demo代码. 页面的展现样式,如下 比较简单,就是红色的背景图,在这10个格子里转动 具体代码如下 html &l ...

  4. len(),range()函数

    len()函数返回字符串.列表.字典.元组等长度 eg1:计算字符串的长度: >>>s='hello good boy doiido' >>>len(s) > ...

  5. c++ 修改stl set中的元素

    set的迭代器it有const修饰符,那么对它元素的修改就必然不能成功了.但是有时候遇到要修改stl set元素的问题,这个问题一般的解决方法是先erase这个元素,然后再insert,这样效率很低, ...

  6. 做什么职业,也别做程序员,尤其是Java程序员

    千万别做程序员,尤其别做Java这种门槛低,入门快的程序员(别跟我说Java搞精通了也很牛之类的,原因不解释,做5年以上就知道了),程序员本来就是我见过最坑爹的职业了...Java程序员更是,现在满地 ...

  7. CodeForces - 156D:Clues(矩阵树定理&并查集)

    题意:给定N点,M边,求添加最少的边使之变为连通图的方案数. 思路:注意题目给出的M边可能带环,即最后生成的不一定是一棵树.但是影响不大.根据矩阵树定理,我们知道生成树的数量=N^(N-2),即点数^ ...

  8. LeetCode Output Contest Matches

    原题链接在这里:https://leetcode.com/problems/output-contest-matches/description/ 题目: During the NBA playoff ...

  9. 「LOJ#10051」「一本通 2.3 例 3」Nikitosh 和异或(Trie

    题目描述 原题来自:CODECHEF September Challenge 2015 REBXOR 1​​≤r​1​​<l​2​​≤r​2​​≤N,x⨁yx\bigoplus yx⨁y 表示 ...

  10. QString的拼接

    QString的append()函数则提供了类似的操作,例如: 1. str = "User: ";     2. str.append(userName);     3. str ...