I have these two classes that implement single table inheritance strategy:
@Entity
@Table(name = "tableA")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("A")
class A {
...
}
@Entity
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("B")
class B extends A {
...
}
When I create a query to fetch all A entities, it brings me B entities as well. How to fetch only entities of type A?
You could make a generic abstract base class and make both A and B extend base, like:
@Entity
@Table(name = "tableA")
@DiscriminatorColumn(name="`type`")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
abstract class Base {
...
}
@Entity
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("A")
class A extends Base {
...
}
@Entity
@DiscriminatorColumn(name = "type")
@DiscriminatorValue("B")
class B extends Base {
...
}
(note that SINGLE_TABLE is the default strategy so the annotation parameter could be omitted).
or if JPA2 were supported, you could just make use of:
SELECT a FROM A a WHERE TYPE(a) = A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With