Search code examples
javajpajakarta-eeannotations

JPA annotation @DiscriminatorValue on root entity does not return expected results or returns all records


I have following entities:

@Table(name="Animal")
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorValue("Animal")
public class Animal{
// code brevity
}

@Entity
@Discriminatorvalue("Dog")
public class Dog extends Animal{
// code brevity
}

So when I run the jpa query entityManager.createQuery("from Animal").getResultList(), it returns me all the records in Animal table where DTYPE in ('Animal', 'Dog') instead of where DTYPE in('Animal'). How can I get records returned where DYTPE = 'Animal' only?


Solution

  • Filter from Animal means instances of type Animal. Any instance of type Dog is also an instance of type Animal and will be also selected. This works correct. And if you later on have more subclasses and select from Animal, you again will get all instances including subclasses.

    If you want to exclude instances of type Dog, you should do that explicitly in your query.

    I'd suggest that you change your model and don't use any discriminator for the base class. Thus you will avoid such incorrect expectations: No developer in your team will expect that selection from Animal will select only part of the records; everyone will understand that select will return all entities of all subclasses. Use discriminator values for subclasses only.