一、结构

For example, you can map a class hierarchy to a single table, but, for a particular subclass, switch to a separate table with a foreign key–mapping strategy, just as with table-per-subclass.

二、代码

1.

 package org.jpwh.model.inheritance.mixed;

 import org.jpwh.model.Constants;

 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
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.mixed;

 import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SecondaryTable;
import javax.validation.constraints.NotNull; @Entity
@DiscriminatorValue("CC")
@SecondaryTable(
name = "CREDITCARD",
pkJoinColumns = @PrimaryKeyJoinColumn(name = "CREDITCARD_ID")
)
public class CreditCard extends BillingDetails { @NotNull // Ignored by JPA for DDL, strategy is SINGLE_TABLE!
@Column(table = "CREDITCARD", nullable = false) // Override the primary table
protected String cardNumber; @Column(table = "CREDITCARD", nullable = false)
protected String expMonth; @Column(table = "CREDITCARD", nullable = false)
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;
}
}

3.

 package org.jpwh.model.inheritance.mixed;

 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;
}
}

4.At runtime, Hibernate executes an outer join to fetch BillingDetails and all sub-class instances polymorphically:

 select
ID, OWNER, ACCOUNT, BANKNAME, SWIFT,
EXPMONTH, EXPYEAR, CARDNUMBER,
BD_TYPE
from
BILLINGDETAILS
left outer join CREDITCARD on ID=CREDITCARD_ID

5. If you have an exceptionally wide class hierarchy, the outer join can become a problem. Some data-base systems (Oracle, for example) limit the number of tables in an outer join operation. For a wide hierarchy, you may want to switch to a different fetching strategy that executes an immediate second SQL select instead of an outer join.

Switching the fetching strategy for this mapping isn’t available in JPA or Hibernate annotations at the time of writing, so you have to map the class in a native Hibernate XML file:

FetchSelect.hbm.xml

 <?xml version="1.0"?>
<hibernate-mapping xmlns="http://www.hibernate.org/xsd/orm/hbm"
package="org.jpwh.model.inheritance.mixed"
default-access="field"> <class name="BillingDetails"
abstract="true">
<id name="id">
<generator class="native"/>
</id>
<discriminator column="BD_TYPE" type="string"/>
<property name="owner"
not-null="true"/> <subclass name="CreditCard"
discriminator-value="CC">
<join table="CREDITCARD" fetch="select">
<key column="CREDITCARD_ID"/>
<property name="cardNumber"
column="CARDNUMBER"
not-null="true"/> <property name="expMonth"
column="EXPMONTH"
not-null="true"/>
<property name="expYear"
column="EXPYEAR"
not-null="true"/>
</join>
</subclass> <subclass name="BankAccount"
discriminator-value="BA">
<property name="account"
not-null="false"/>
<property name="bankname"
not-null="false"/>
<property name="swift"
not-null="false"/>
</subclass>
</class> </hibernate-mapping>

三、优点

1.Remember that InheritanceType.SINGLE_TABLE enforces all columns of sub-classes to be nullable. One of the benefits of this mapping is that you can now declare columns of the CREDITCARD table as NOT NULL , guaranteeing data integrity.

四、缺点

代码中的第5点

JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-006Mixing inheritance strategies(@SecondaryTable、@PrimaryKeyJoinColumn、<join fetch="select">)的更多相关文章

  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-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 ...

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

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

  4. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-004Table per class hierarchy(@Inheritance..SINGLE_TABLE)、@DiscriminatorColumn、@DiscriminatorValue、@DiscriminatorFormula)

    一.结构 You can map an entire class hierarchy to a single table. This table includes columns for all pr ...

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

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

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

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

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

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

  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. LeetCode OJ:Sort Colors(排序颜色)

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...

  2. hdoj-1031-Design T-Shirt

    题目链接 /* 两次排序,搞定 */ #include <cstring> #include <iostream> #include <algorithm> usi ...

  3. python在字符串中查找字符

    两类函数: find(),rfind() index(),rindex() 找到了都返回下标. find找不到返回-1,index找不到抛出ValueError. 带r的表示从右向左找. 都可以使用第 ...

  4. Python ord()与chr()函数

    chr():十进制或十六进制数(0-255)转成对应的ASCII字符. ord():ASCII字符转成对应的十进制数. 一个小性质:ASCII表中大写字母排在前面小写排在后面,相差32. 比如: or ...

  5. 【pandas】pandas.DataFrame.rename()---重置索引名称

    官方文档 github地址 例子: 创建DataFrame ### 导入模块 import numpy as np import pandas as pd import matplotlib.pypl ...

  6. oracle中merge的用法,以及各版本的区别 Create

    Merge是一个非常有用的功能,类似于Mysql里的insert into on duplicate key. Oracle在9i引入了merge命令,通过这个merge你能够在一个SQL语句中对一个 ...

  7. 在系统学习javaEE开发的颠覆者Springboot时遇到的localhost无法访问的问题

    就是新建了一个Springboot项目,但是无法正常访问. 关闭防火墙试了,mvn方式启动试了,换端口试了.然后用Tomcat的start.bat测试发现localhost是可以访问的. 上网找到各种 ...

  8. keepalived 检测脑裂切换脚本

    #!/bin/bash count=0 run1=`curl -I 192.168.30.12:8000 | grep "200 OK" | wc -l` run2=`curl - ...

  9. laravel的小坑

    写控制器的名的时候只能出现一个首写大写字母, 后面的都为小写字母 否则会报找不到该控制器的错误

  10. (转)AppCan中调用系统浏览器打开网页

    <!DOCTYPE html> <html> <head> <style>body{ background:#fff; font-size:30px;} ...