Kesha Williams introduces the concept of inheritance and highlights the four inheritance mapping strategies in JPA, which are mapped superclass, single table, joined table, and table per class.
- [Instructor] What if you unexpectedly received an inheritance that instantly turned you into a billionaire? That would be nice, wouldn't it? Well, inheritance can be just as nice in the Java world. There are four inheritance mapping strategies in JPA, mapped superclass, single table, joined table, and table per class. In Java, different kinds of objects often share attributes in common with each other. When there are several objects that share certain things in common, common attributes can be moved up or generalized in a base class, where the more specific or specialized attributes can exist in the child class.
This process is called inheritance. Inheritance allows classes to inherit commonly used state and behavior from other classes. In the Trackzilla application, the inheritance relationship introduced is between the ticket, bug, and enhancement. The common attributes like title and description were moved up to the superclass. Inheritance exemplifies code reuse. Each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.
In relational databases, inheritance is nonexistent. A table cannot inherit from another table. A column cannot inherit from another column. So how do we maintain an inheritance relationship when saving Java objects to a relational database. Thanks to JPA, there are several options for organizing an object model into a flat database structure. I'm going to teach you about four strategies for doing so, mapped superclass, single table, joined table, table per class.
No one strategy is better than the other, and each one has its pros and cons, which I will share with you. You just have to decide which one is best for your particular use case. In order to implement an inheritance strategy in JPA, all Java objects must be entities represented by the @Entity annotation. Entities are objects that live in a database and have the ability to be mapped to a class. All entities are managed by the entity manager.
The entity manager is useful because it is used to create and remove entity instances, to find entities by primary key, and to query over entities. Inheritance is a useful feature in object-oriented programming because it allows for code reuse.
- Inheriting entities
- Mapping a superclass
- Querying through JPA
- Defining query parameters
- Creating a compile-time named query
- Using native queries
- Creating stored procedures
- Using the Criteria API
- Refining query results
- Switching between persistence providers