Page 5 of 6
The power of inheritance
An entity can extend the following:
- Another entity -- either concrete or abstract.
- Another non-entity, supplying behavior or non-persistence state. The attributes you inherit from a non-entity are not persisted.
- Mapped superclasses, supplying common entity state. Tables in a database have similar fields, but tables are not related to
each other.
Let's
have a look into the various types of inheritance JPA offers. For this
scenario, assume that there are two types of customer: a normal
customer who buys products from a physical store and an online customer
who buys products over the Internet.
Single-table inheritance
In single-table inheritance, all the entities in the hierarchy are stored in a single table. Single-table inheritance is the default strategy. Thus, you
could omit the @Inheritance
annotation in the example code in Listing 12 and get the same result.
In the example application, both ordinary and online customers are stored in the CUSTOMER table, as shown in Table 2.
Table 2. Single-table inheritance mapping strategy
ENTITY
TABLE NAME
Customer |
CUSTOMER |
OnlineCustomer |
CUSTOMER |
The Customer
entity has custId
, firstName
, lastName
, custType
, and address information, whereas the OnlineCustomer
entity has only a website
attribute and otherwise extends all features of Customer
. This strategy should be reflected in the superclass, as in Listing 12.
Listing 12. A sample superclass in single-table inheritance
@Entity(name = "CUSTOMER")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="CUST_TYPE", discriminatorType=DiscriminatorType.STRING,length=10)
@DiscriminatorValue("RETAIL")
public class Customer implements Serializable{
@Id
@Column(name = "CUST_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long custId;
@Column(name = "FIRST_NAME", nullable = false,length = 50)
private String firstName;
@Column(name = "LAST_NAME", length = 50)
private String lastName;
@Embedded
private Address address = new Address();
@Column(name = "CUST_TYPE", length = 10)
private String custType;
................
}
For the time being, ignore the DiscriminatorColumn
and DiscriminatorValue
annotations; you'll see how those work later. The OnlineCustomer
entity will be a normal entity class that extends Customer
class, as shown in Listing 13.
Listing 13. A sample subclass in single-table inheritance
@Entity(name = "ONLINECUSTOMER") //Name of the entity
@DiscriminatorValue("ONLINE")
public class OnlineCustomer extends Customer{
@Column(name = "WEBSITE", length = 100)
private String website;
............
}
Now you must create a Customer
object and an OnlineCustomer
object and persist them, as in Listing 14.
Listing 14. Persisting objects in single-table inheritance
......................
userTransaction.begin();
//inserting Customer
Customer customer = new Customer();
customer.setFirstName("Charles");
customer.setLastName("Dickens");
customer.setCustType("RETAIL");
customer.getAddress().setStreet("10 Downing Street");
customer.getAddress().setAppt("1");
customer.getAddress().setCity("NewYork");
customer.getAddress().setZipCode("12345");
em.persist(customer);
//Inserting Online customer
OnlineCustomer onlineCust = new OnlineCustomer();
onlineCust.setFirstName("Henry");
onlineCust.setLastName("Ho");
onlineCust.setCustType("ONLINE");
onlineCust.getAddress().setStreet("1 Mission Street");
onlineCust.getAddress().setAppt("111");
onlineCust.getAddress().setCity("NewYork");
onlineCust.getAddress().setZipCode("23456");
onlineCust.setWebsite("www.amazon.com");
em.persist(onlineCust);
userTransaction.commit();
......................
If you have a look into the CUSTOMER table now, you will find two records. The query in Listing 15 should return you the list
of online customers from the data store.
Listing 15. Fetching only the subclass in single-table inheritance
..............
Query query = em.createQuery("SELECT customer FROM ONLINECUSTOMER customer");
List<OnlineCustomer> list= query.getResultList();
.................
If the CUSTOMER table stores both the Customer
and the OnlineCustomer
data, how will JPA distinguish one from the other? How will it fetch only the online customers? In fact, JPA cannot do this
unless you provide it with a hint. That's the significance of the @DiscriminatorColumn
. It tells the CUSTOMER table which column distinguishes a CUSTOMER from an ONLINE CUSTOMER. @DiscriminatorValue
indicates what value identifies a CUSTOMER and an ONLINE CUSTOMER. The @DiscriminatorValue
annotation needs to be provided in the superclass as well as in all the subclasses.
When you want to fetch online customers, JPA silently queries the data store as in Listing 16.
Listing 16. Distinguishing objects stored in a single table
SELECT t0.CUST_ID, t0.CUST_TYPE, t0.LAST_UPDATED_TIME, t0.APPT, t0.city, t0.street, t0.ZIP_CODE, t0.FIRST_NAME, t0.LAST_NAME, t0.WEBSITE FROM CUSTOMER t0
WHERE t0.CUST_TYPE = 'ONLINE'
分享到:
相关推荐
After completing Pro JPA 2 in Java EE 8, you will have a full understanding of JPA and be able to successfully code applications using its annotations and APIs. The book also serves as an excellent ...
This tutorial provides a basic understanding of how to store a copy of database objects into temporary memory using JAVA Persistence API (JPA).
在本文中,我们将深入探讨事务的基本原理、类型、特性以及在实际开发中的应用,尤其是与Java JPA(Java Persistence API)的结合。 首先,让我们了解什么是事务。在数据库管理中,事务是一系列数据库操作的逻辑单元...
Explore simplified but powerful data access techniques including JPA (Java Persistence Architecture) repositories and NoSQL data access Who This Book Is For If you are a Java developer who is looking ...
在技术细节方面,文章"Understanding Java Method Invocation with Invokedynamic"讨论了Java 7中引入的invokedynamic指令。这条指令使得Java在运行时可以动态地解决方法调用,为Java虚拟机带来了动态类型语言支持。...
46.1. Understanding Auto-configured Beans 46.2. Locating Auto-configuration Candidates 46.3. Condition Annotations 46.3.1. Class Conditions 46.3.2. Bean Conditions 46.3.3. Property Conditions 46.3.4. ...
第十二章“Understanding clustering”介绍了JBoss的集群化技术,包括集群架构、节点通信机制、负载均衡策略等内容,为构建高可用、可扩展的分布式系统提供了理论基础。而第十三章可能进一步深入讲解了集群的具体...
5. **Spring Persistence**:Spring框架的持久化模块涵盖了对数据存储的支持,包括JDBC、JPA(Java Persistence API)和Hibernate等ORM工具。它提供了统一的API,简化了数据访问层的开发。 6. **Spring AOP**:前面...
Chapter 5. Building Spring web applications 5.1. Getting started with Spring MVC 5.1.1. Following the life of a request 5.1.2. Setting up Spring MVC 5.1.3. Introducing the Spittr application 5.2. ...
- **Java 持久化 API (JPA)**:Seam 与 JPA 密切结合,提供了对实体管理、查询语言等方面的强大支持,帮助开发者更容易地进行数据访问和管理。 8. **Seam 管理的事务和持久化 (Seam-Managed Transactions and ...
5. **输入/输出(I/O)系统**:Java提供了丰富的I/O流类库,如FileInputStream、FileOutputStream、BufferedReader、PrintWriter等,支持文件操作和网络通信。 6. **集合框架**:Java的`java.util`包中包含了多种...
Not Using Commons Logging ................................................................... 12 Using SLF4J ..............................................................................................
Not Using Commons Logging ................................................................... 12 Using SLF4J ..............................................................................................