javahibernatejpasingle-table-inheritancediscriminator

Hibernate ignoring discriminator column - always using 'dtype'


I have a strange situation in my SINGLE_TAB inheritance Hibernate config whereby the @DiscriminatorColumn seems to be ignored and the query is always defaulting back to the 'dtype' column. It's like the behaviour I would see when I had not included the annotation at all (the default column name being 'dtype').

Base entity:

@Entity
@Table(name = "post")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(columnDefinition = "post_type", discriminatorType = DiscriminatorType.STRING)
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "title")
    private String title;

    @Column(name = "body")
    private String body;

    @NotNull
    @Column(name = "post_type", insertable = false, updatable = false)
    private String postType;

    // other simple columns



    // ommit getters/setters + hashcode etc
}

Subclass entity:

@Entity
@DiscriminatorValue(value = "EVENT")
public class Event extends Post {

    // ommitted basic methods, no extra config

}

I also need access to the discriminator value itself within each object (the postType field). I still have the same behaviour even if I remove it so it doesn't seem to be the cause.

When I try to do a query on the subclass through a JPA repository:

public interface EventRepository extends JpaRepository<Event, Integer> {
    List<Event> findAll();
}

Hibernate generates the query:

select post0_.id as id2_4_, post0_.bodyl as body_bod3_4_, post0_.title as title12_4_ 
from post post0_ 
where post0_.dtype='EVENT'

which of course generates an error as 'dtype' doesn't exist in the table.

The strange thing is that if I use @DiscriminatorFormula("post_type") on the Post entity instead, everything seems to work. It is however slower so I would prefer to use the @DiscriminatorColumn as it should fit my needs exactly.

I am using Hibernate 5.2.10-FINAL and Spring Data JPA 1.11.4 (or generally the latest of hopefully everything).

Any ideas on what could be causing this?


Solution

  • I'm think you have this problem because you specified wrong parameter of @DiscriminatorColumn anotation, you should use name instead of columnDefinition.