JPA (Java Persistence API) provides several annotations for mapping 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 managed 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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3