I have an abstract base class:
@Inheritance(strategy = InheritanceType.JOINED)
@Getter
@Setter
@Entity
@ToString
public abstract class BillingDetails {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "pk_for_inheritance")
Long Id;
@NotNull
private String owner;
}
and one subclass extending base class
@Entity
@Getter
@Setter
@ToString(callSuper = true)
public class CreditCard extends BillingDetails{
@Basic(optional = false)
private String cardNumber;
@Basic(optional = false)
private LocalDate expDate;
@Basic(optional = false)
private String cardKey;
}
when I query against base Entity BillingDetails and print results like so:
List<BillingDetails> details=billingDetailsRepository.findAll();
details.forEach(System.out::println);
I get the following output:
CreditCard(super=BillingDetails(Id=1, owner=Mehmet Dogan), cardNumber=6145 1233 4577 2360, expDate=2022-05-03, cardKey=673)
My question is: Although I understand in joined strategy hibernates joins related base and sub tables ,How is it possible that I can print properties of subclass CreditCard when my result list is of type BillingDetails and only Id and Owner properties are declared in my base class ?
CodePudding user response:
What I have missed here was I think polymorphism. When I tried to get Class of results like
List<BillingDetails> details=billingDetailsRepository.findAll();
details.forEach(x-> System.out.println(x.getClass()));
I got the following output :
class com.rumlor.domainmodelmapping.models.inheritancemodels.CreditCard
so somehow I missed somewhere even if results are cast to List Of BillingDetails ,Hibernate polymorphed every sub instance to base entity for me. additional check :
CreditCard card= (CreditCard) details.get(0);
System.out.println(card);
result :
CreditCard(super=BillingDetails(Id=1, owner=Mehmet Dogan), cardNumber=6145 1233 4577 2360, expDate=2022-05-03, cardKey=673)