JPA (Java Persistence API) provides several annotations to map Java classes to database tables. One such useful annotation is @MappedSuperclass, which is used to designate a class whose properties must be inherited by other entity classes, but which is not an entity itself. Let's explore the usefulness of this annotation through a practical example involving classes such as Vehicle, Car and Motorcycle.
What is @MappedSuperclass?
The @MappedSuperclass annotation is used to indicate that a class should not be an independent entity, but that its attributes should be inherited by other classes that are entities. This is useful when you want to share common attributes between multiple entities without creating a separate table for the base class.
Main features:
Practical Example
Let's create an example with a class hierarchy for Vehicle, Car and Motorcycle, where Vehicle is the superclass.
1. Base Class: Vehicle
import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class Veiculo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String marca; private String modelo; private int ano; // Getters e Setters }
2. Subclass: Car
import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "carro") public class Carro extends Veiculo { private int quantidadePortas; // Getters e Setters }
3. Subclass: Motorcycle
import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "motocicleta") public class Motocicleta extends Veiculo { private boolean temSidecar; // Getters e Setters }
Table Mapping
With the above classes, JPA will create the following tables in the database:
The Vehicle table does not exist in the database, as the Vehicle class is just a superclass and not an entity.
Benefits of using @MappedSuperclass
Considerations
If you want the superclass to also be an entity (e.g. for direct queries), use the @Inheritance inheritance strategy instead of @MappedSuperclass.
@MappedSuperclass is ideal for situations where the base class does not need to be persisted as an individual entity, but its properties are relevant to multiple entities.
Conclusion
The @MappedSuperclass annotation is a powerful tool for creating reusable class hierarchies in JPA. In the example above, we were able to centralize the common attributes in Vehicle and, at the same time, maintain the flexibility and independence of the Car and Motorcycle entities. This approach promotes a cleaner, more modular design, especially in systems with multiple entities that share similar characteristics.
The above is the detailed content of Understanding @MappedSuperclass in JPA. For more information, please follow other related articles on the PHP Chinese website!