一、代码

1.

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

 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.TABLE_PER_CLASS)
public abstract class BillingDetails { @Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; @ManyToOne(fetch = FetchType.LAZY)
protected User user; @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;
} public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} public void pay(int amount) {
// NOOP
} // ...
}

2.

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

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

3.

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

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

4.

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

 import org.jpwh.model.Constants;

 import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set; @Entity
@Table(name = "USERS")
public class User { @Id
@GeneratedValue(generator = Constants.ID_GENERATOR)
protected Long id; @NotNull
protected String username; @OneToMany(mappedBy = "user")
protected Set<BillingDetails> billingDetails = new HashSet<>(); 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 Set<BillingDetails> getBillingDetails() {
return billingDetails;
} public void setBillingDetails(Set<BillingDetails> billingDetails) {
this.billingDetails = billingDetails;
} // ...
}

5.测试

 package org.jpwh.test.inheritance;

 import org.jpwh.env.JPATest;
import org.jpwh.model.inheritance.associations.onetomany.BankAccount;
import org.jpwh.model.inheritance.associations.onetomany.BillingDetails;
import org.jpwh.model.inheritance.associations.onetomany.CreditCard;
import org.jpwh.model.inheritance.associations.onetomany.User;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import javax.persistence.EntityManager;
import javax.transaction.UserTransaction; import static org.testng.Assert.assertEquals; public class PolymorphicOneToMany extends JPATest { @Override
public void configurePersistenceUnit() throws Exception {
configurePersistenceUnit("PolymorphicOneToManyPU");
} @Test
public void storeAndLoadItemBids() throws Exception {
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager(); BankAccount ba = new BankAccount(
"Jane Roe", "445566", "One Percent Bank Inc.", "999"
);
CreditCard cc = new CreditCard(
"John Doe", "1234123412341234", "06", "2015"
);
User johndoe = new User("johndoe"); johndoe.getBillingDetails().add(ba);
ba.setUser(johndoe); johndoe.getBillingDetails().add(cc);
cc.setUser(johndoe); em.persist(ba);
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); for (BillingDetails billingDetails : user.getBillingDetails()) {
billingDetails.pay(123);
}
assertEquals(user.getBillingDetails().size(), 2);
} tx.commit();
em.close(); } finally {
TM.rollback();
}
} }

JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-009Polymorphic collections(@OneToMany(mappedBy = "user")、@ManyToOne、)的更多相关文章

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

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

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

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

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

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

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

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

  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. 26 python 并发编程之多进程理论

    一 什么是进程 进程:正在进行的一个过程或者说一个任务.而负责执行任务则是cpu. 举例(单核+多道,实现多个进程的并发执行): egon在一个时间段内有很多任务要做:python备课的任务,写书的任 ...

  2. Hibernate Validator验证框架中@NotEmpty、@NotBlank、@NotNull 的区别

    Hibernate Validator验证框架中@NotEmpty.@NotBlank.@NotNull的主要使用情况 @NotEmpty  用在集合类上面 @NotBlank   用在String上 ...

  3. New Concept English three (57)

    28w/m 54errors I stopped to let the car cool off and to study the map. I had expected to be near my ...

  4. WC2019 滚粗记

    离开的时候一定是笑着离开的 不然就再也回不来了 广州二中,七月再见

  5. NET Core 2.0利用MassTransit集成RabbitMQ

    NET Core 2.0利用MassTransit集成RabbitMQ https://www.cnblogs.com/Andre/p/9579764.html 在ASP.NET Core上利用Mas ...

  6. 四、python沉淀之路--元组

    一.元组基本属性 1.元组不能被修改,不能被增加.不能被删除 2.两个属性 tu.count(22)       #获取指定元素在元组中出现的次数tu.index(22)      #获取指定元素的缩 ...

  7. Object-C类、方法、构造函数(2)

    Object-C 代码分为三部分:.h文件..m文件及调用文件 .h源文件 #import <Foundation/Foundation.h> @interface Student:NSO ...

  8. 蓝桥杯 算法训练 ALGO-124 数字三角形

    算法训练 数字三角形   时间限制:1.0s   内存限制:256.0MB   问题描述 (图3.1-1)示出了一个数字三角形. 请编一个程序计算从顶至底的某处的一条路 径,使该路径所经过的数字的总和 ...

  9. Spring Boot 集成Swagger2生成RESTful API文档

    Swagger2可以在写代码的同时生成对应的RESTful API文档,方便开发人员参考,另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API. 使用Spring Boot可 ...

  10. 四川第七届 I Travel(bfs)

    Travel The country frog lives in has nn towns which are conveniently numbered by 1,2,…,n1,2,…,n. Amo ...