一、结构

二、代码

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. Linux下添加,删除,修改,查看用户和用户组

      linux下添加,删除,修改,查看用户和用户组 1,创建组 groupadd test 增加一个test组 2,修改组 groupmod -n test2 test 将test组的名子改成test ...

  2. ES6-浏览器运行环境配置方法

    现在ES6用的越来越多,想要学习使用ES6,只需简单搭建引入几个js即可运行ES6代码 但是需要基本的服务器环境下运行(如http://10.12.8.161:8047/js-test/export/ ...

  3. python3 之 格式化json

    import json json_string = None with open("json_file.json") as f: json_string = f.read() tr ...

  4. 侯捷STL学习(十)--容器hashtable探索(unordered set/map)

    layout: post title: 侯捷STL学习(十) date: 2017-07-23 tag: 侯捷STL --- 第二十三节 容器hashtable探索 hashtable冲突(碰撞)处理 ...

  5. Python函数(七)-匿名函数

    函数就是变量,定义一个函数就是把一个函数体赋值给一个函数名,函数和变量的回收机制也是一样的 匿名函数不需要指定函数名,只需要有函数体,然后把这个函数体赋给一个变量 Python中使用lambda来创建 ...

  6. PowerDesigner生成sql脚本时去掉双引号并把字段名设为大写

    Database菜单—Edit Current RDBMS 找到Script---sql—Format--- CaseSensitivityUsingQuote,把它设置为NO 这样再用sql pre ...

  7. How to clear fmadm log or FMA faults log (ZT)

    Here are the step by step of clearing the FMA faults on most of Oracle/Sun server. Work perfectly on ...

  8. 通过在Oracle子表外键上建立索引提高性能

    根据我的经验,导致死锁的头号原因是外键未加索引(第二号原因是表上的位图索引遭到并发更新).在以下两种情况下,Oracle在修改父表后会对子表加一个全表锁: 1)如果更新了父表的主键(倘若遵循关系数据库 ...

  9. Spring装配各种类型bean

    一.单属性值的装配 //setter注入,提供无参构造器,提供setXX方法 <property name="" value=""></pro ...

  10. Solr查询错误

    报错: Exception in thread "main" java.lang.VerifyError: Bad return type Exception Details: L ...