Hibernate JPA @Polymorphism Example
The @Polymorphism annotation is used to define the PolymorphismType Hibernate will apply to entity hierarchies.
There are two possible PolymorphismType options:
EXPLICIT
The currently annotated entity is retrieved only if explicitly asked.
IMPLICIT
The currently annotated entity is retrieved if any of its super entities are retrieved. This is the default option.
However, you can even query interfaces or base classes that don’t belong to the JPA entity inheritance model.
For instance, considering the following DomainModelEntity interface:
Example : DomainModelEntity interface
public interface DomainModelEntity<ID> {
ID getId();
Integer getVersion();
}
If we have two entity mappings, a Book and a Blog, and the Blog entity is mapped with the @Polymorphism annotation and taking the PolymorphismType.EXPLICIT setting:
Example: @Polymorphism entity mapping
@Entity(name = "Event")
public static class Book implements DomainModelEntity<Long> {
@Id
private Long id;
@Version
private Integer version;
private String title;
private String author;
//Getter and setters omitted for brevity
}
@Entity(name = "Blog")
@Polymorphism(type = PolymorphismType.EXPLICIT)
public static class Blog implements DomainModelEntity<Long> {
@Id
private Long id;
@Version
private Integer version;
private String site;
//Getter and setters omitted for brevity
}
There are two possible PolymorphismType options:
EXPLICIT
The currently annotated entity is retrieved only if explicitly asked.
IMPLICIT
The currently annotated entity is retrieved if any of its super entities are retrieved. This is the default option.
Implicit and explicit polymorphism
By default, when you query a base class entity, the polymorphic query will fetch all subclasses belonging to the base type.However, you can even query interfaces or base classes that don’t belong to the JPA entity inheritance model.
For instance, considering the following DomainModelEntity interface:
Example : DomainModelEntity interface
public interface DomainModelEntity<ID> {
ID getId();
Integer getVersion();
}
If we have two entity mappings, a Book and a Blog, and the Blog entity is mapped with the @Polymorphism annotation and taking the PolymorphismType.EXPLICIT setting:
Example: @Polymorphism entity mapping
@Entity(name = "Event")
public static class Book implements DomainModelEntity<Long> {
@Id
private Long id;
@Version
private Integer version;
private String title;
private String author;
//Getter and setters omitted for brevity
}
@Entity(name = "Blog")
@Polymorphism(type = PolymorphismType.EXPLICIT)
public static class Blog implements DomainModelEntity<Long> {
@Id
private Long id;
@Version
private Integer version;
private String site;
//Getter and setters omitted for brevity
}
Comments
Post a Comment