一、结构

二、代码

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. ie-9 以下ajax无法跨域的问题。只要add:jQuery.support.cors=true;即可

    if (!jQuery.support.cors && window.XDomainRequest) { var httpRegEx = /^https?:\/\//i; var ge ...

  2. Python文件练习

    练习内容: 使用Python管理ini文件:实现查询,添加,删除,保存操作. 练习目的: 1.掌握文件基本操作 2.认识ini文件 3.了解ConfigParser: ini配置文件格式: 节:[se ...

  3. 2018.7.26 学会说NO,拒绝道德绑架。

    一.领导交给你一项不属于你工作范围的工作,是否需要拒绝,你可以考虑以下问题: 1.这是与我核心能力相关的工作吗?是,接受:否,进入下一条: 2.它能帮助我拓展我核心能力的边界,或是我感兴趣的吗?是,接 ...

  4. ENTRYPOINT 与 CMD

    在Dockerfile中 ENTRYPOINT 只有最后一条生效,如果写了10条,前边九条都不生效 ENTRYPOINT 的定义为运行一个Docker容器像运行一个程序一样,就是一个执行的命令 两种写 ...

  5. 《Javascript高级程序设计》阅读记录(三):第五章 上

    这个系列以往文字地址: <Javascript高级程序设计>阅读记录(一):第二.三章 <Javascript高级程序设计>阅读记录(二):第四章 这个系列,我会把阅读< ...

  6. 使用swing构建一个界面(包含flow ,Border,Grid,card ,scroll布局)

    package UI; import java.awt.BorderLayout;import java.awt.CardLayout;import java.awt.Cursor;import ja ...

  7. C++对C语言的拓展(3)—— 默认参数和占位参数

    通常情况下,函数在调用时,形参从实参那里取得值.对于多次调用同一函数同一 实参时,C++给出了更简单的处理办法.给形参以默认值,这样就不用从实参那里取值了. 1.单个默认参数 若填写参数,使用你填写的 ...

  8. 在winform下实现左右布局多窗口界面的方法(二)

    这篇文章主要介绍了在winform下实现左右布局多窗口界面的方法之续篇 的相关资料,需要的朋友可以参考下 在上篇文章在winform下实现左右布局多窗口界面的方法(一)已经实现了左右布局多窗口界面,今 ...

  9. asp.net 打印控件使用方法

    打印的效果及控制性虽然不是很好,但是也能勉强使用,应付一般的打印还是 可以的了.代码如下所示: 代码 复制代码 代码如下: //调用PrintControl.ExecWB(?,?)实现直接打印和打印预 ...

  10. mongo之map-reduce笔记

    package com.sy.demo; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import ...