一、结构

二、代码

1.

 package org.jpwh.model.inheritance.associations.manytoone;

 import org.jpwh.model.Constants;

 import javax.persistence.*;
import javax.validation.constraints.NotNull; // Can not be @MappedSuperclass when it's a target class in associations!
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class BillingDetails { protected Long id; @NotNull
protected String owner; protected BillingDetails() {
} protected BillingDetails(String owner) {
this.owner = owner;
} // Use property instead of field access, so calling getId() doesn't initialize a proxy!
@Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
public Long getId() {
return id;
} private void setId(Long id) {
this.id = id;
} public String getOwner() {
return owner;
} public void setOwner(String owner) {
this.owner = owner;
} public void pay(int amount) {
// NOOP
}
}

2.

 package org.jpwh.model.inheritance.associations.manytoone;

 import javax.persistence.Entity;
import javax.validation.constraints.NotNull; @Entity
public class CreditCard extends BillingDetails { @NotNull
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;
} }

3.

 package org.jpwh.model.inheritance.associations.manytoone;

 import javax.persistence.Entity;
import javax.validation.constraints.NotNull; @Entity
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.

 package org.jpwh.model.inheritance.associations.manytoone;

 import org.jpwh.model.Constants;

 import javax.persistence.*;
import javax.validation.constraints.NotNull; @Entity
@Table(name = "USERS")
public class User { @Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; @NotNull
protected String username; @ManyToOne(fetch = FetchType.LAZY)
protected BillingDetails defaultBilling; public User() {
} public User(String username) {
this.username = username;
} public Long getId() {
return id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public BillingDetails getDefaultBilling() {
return defaultBilling;
} public void setDefaultBilling(BillingDetails defaultBilling) {
this.defaultBilling = defaultBilling;
} // ...
}

5.测试

 package org.jpwh.test.inheritance;

 import org.jpwh.env.JPATest;
import org.jpwh.model.inheritance.associations.manytoone.BillingDetails;
import org.jpwh.model.inheritance.associations.manytoone.CreditCard;
import org.jpwh.model.inheritance.associations.manytoone.User;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import javax.persistence.EntityManager;
import javax.transaction.UserTransaction; import static org.testng.Assert.*; public class PolymorphicManyToOne extends JPATest { @Override
public void configurePersistenceUnit() throws Exception {
configurePersistenceUnit("PolymorphicManyToOnePU");
} @Test
public void storeAndLoadItemBids() throws Exception {
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager(); CreditCard cc = new CreditCard(
"John Doe", "1234123412341234", "06", "2015"
);
User johndoe = new User("johndoe");
johndoe.setDefaultBilling(cc); em.persist(cc);
em.persist(johndoe); tx.commit();
em.close(); Long USER_ID = johndoe.getId(); tx.begin();
em = JPA.createEntityManager();
{
User user = em.find(User.class, USER_ID); // Invoke the pay() method on a concrete subclass of BillingDetails
user.getDefaultBilling().pay(123);
assertEquals(user.getDefaultBilling().getOwner(), "John Doe");
} tx.commit();
em.close(); tx.begin();
em = JPA.createEntityManager();
{
User user = em.find(User.class, USER_ID); BillingDetails bd = user.getDefaultBilling(); assertFalse(bd instanceof CreditCard); // Don't do this, ClassCastException!
// CreditCard creditCard = (CreditCard) bd;
}
{
User user = em.find(User.class, USER_ID); //because the defaultBilling property is
// mapped with FetchType.LAZY , Hibernate will proxy the association target.
BillingDetails bd = user.getDefaultBilling(); CreditCard creditCard =
em.getReference(CreditCard.class, bd.getId()); // No SELECT! assertTrue(bd != creditCard); // Careful!
}
tx.commit();
em.close(); tx.begin();
em = JPA.createEntityManager();
{
User user = (User) em.createQuery(
"select u from User u " +
"left join fetch u.defaultBilling " +
"where u.id = :id")
.setParameter("id", USER_ID)
.getSingleResult(); // No proxy has been used, the BillingDetails instance has been fetched eagerly
CreditCard creditCard = (CreditCard) user.getDefaultBilling();
}
tx.commit();
em.close(); } finally {
TM.rollback();
}
} }

JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-008Polymorphic many-to-one associations(@ManyToOne、@Inheritance、)的更多相关文章

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

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

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

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

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

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

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

  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. power designer 设计数据库生成到oracle数据库

    一.概念模型设计 1. 创建工程,创建概念设计模型,在快捷菜单栏调出 palette 找到表格工具,在主界面中创建表格. 2. 创建出的表格,双击进入设计模式 -------------------- ...

  2. BackBone 源码解读及思考

    说明 前段时间略忙,终于找到时间看看backbone代码. 正如知友们说的那样,backbone简单.随性. 代码简单的看一眼,就能知道作者的思路.因为简单,所以随性,可以很自由的和其他类库大搭配使用 ...

  3. 统计数字noip2007

    7909:统计数字 总时间限制:  1000ms 内存限制:  65536kB 描述 某次科研调查时得到了n个自然数,每个数均不超过1500000000(1.5*109).已知不相同的数不超过1000 ...

  4. 【转】JVM虚拟性能分析

    JDK自带的JAVA性能分析工具.它已经在你的JDK bin目录里了,只要你使用的是JDK1.6 Update7之后的版本.点击一下jvisualvm.exe图标它就可以运行了. 这里是VisualV ...

  5. Spark Shuffle大揭秘

    什么是Shuffle: Shuffle中文翻译为“洗牌”,需要Shuffle的关键原因是某种具有共同特征的数据需要最终汇聚到一个计算节点上进行计算. Shuffle面临的问题: 1. 数据量非常大: ...

  6. 0. LeetCode 开篇

    LeetCode 开篇 很久以前(也许是几天之前,记忆力没那么好),听朋友说过,但是没怎么重视,最近发现自己基础打的不牢(会是会,但是说不出来,说不明白),故借此机会理一理知识点,并复习,巩固相关知识 ...

  7. java服务覆盖率统计 jacoco ant

    ● 下载jacoco.exec.jacocoant.jar.jacocoagent.jar ● jvm启动参数中添加(tomcat服务原理一样) JACOCO_OPTS=JAVA_OPTS=" ...

  8. 蓝桥杯 算法训练 ALGO-145 4-1打印下述图形

     算法训练 4-1打印下述图形   时间限制:1.0s   内存限制:256.0MB 问题描述 使用循环结构打印下述图形,打印行数n由用户输入.打印空格时使用"%s"格式,向pri ...

  9. [转载]Linux C 字符串函数 sprintf()、snprintf() 详解

    一.sprintf() 函数详解 在将各种类 型的数据构造成字符串时,sprintf 的强大功能很少会让你失望. 由于 sprintf 跟 printf 在用法上几乎一样,只是打印的目的地不同而已,前 ...

  10. sleep 和 usleep的实现方法

    一.sleep 和 usleep 1.不属于系统调用,是glibc 库函数实现的: 2.glibc函数库中通过调用内核的nanosleep实现的: 3.内核nanosleep通过调用 hrtimer_ ...