Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch only one kind of entities while using inheritance in hibernate?

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?

like image 352
Carlos Melo Avatar asked Nov 30 '25 00:11

Carlos Melo


1 Answers

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
like image 194
guido Avatar answered Dec 02 '25 14:12

guido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!