一、结构

二、代码

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. MySQL相关日志介绍

    1.MySQL中主要日志如下: ① 错误日志(Log Error) ② 查询日志(Query Log) ③ 二进制日志(Binary Log) 2.相关日志的作用: 1) 错误日志(Error Log ...

  2. scrapy入门实践1

    Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中. 这就是整个Scrapy的架构图了: 各部件职能: Scrapy ...

  3. 冒泡算法-bubble

    冒泡算法在数据只有几个无序时是最快的算法,但是如果全部无序的话就变成了最慢的算法了,时间复杂度为O(n^2) public class bubbleSort { public static void ...

  4. 一步一步使用webpack+react+scss脚手架重构项目

    前几天做了一个项目:[node]记录项目的开始与完成——pipeline_kafka流式数据库管理项目:因为开发时间紧迫,浅略的使用了一下react,感觉这个ui库非常的符合我的口味,现在趁着有空闲时 ...

  5. CommonJS 规范

    CommonJS 是以在浏览器环境之外构建 JavaScript 生态系统为目标而产生的项目,比如在服务器和桌面环境中. 这个项目最开始是由 Mozilla 的工程师 Kevin Dangoor 在2 ...

  6. VS软件版本号定义、规则和相关的Visual Studio插件

    http://blog.csdn.net/cnhk1225/article/details/37500593 软件版本号主要标识了软件的版本,通过其可以了解软件.类库文件的当前版本,使得软件版本控制有 ...

  7. 一、Jmeter的安装

    一.首先安装Jmeter 1.安装java Jmeter是使用java实现的测试工具,在安装Java之前我们需要安装java. 到这里去下载相应的JDK:https://www.java.com/en ...

  8. DropShadowEffect导致下拉框控件抖动

    <!--<Border.Effect> <DropShadowEffect Direction="180" BlurRadius="1" ...

  9. springmvc 加载静态文件失败

    header.jsp,部分代码 <head> <title>QA|VIS_PLATFORM</title> <meta content="width ...

  10. #define和const的区别

    下面使用#define和const定义常量: #define n_define 10 int main(int argc, char* argv[],int _version) { ; int *p= ...