Creating an index in subtype using JPA

Hi!

Can you help me, please? I’m trying to get rid of outdated hibernate annotations but having trouble with creating the index.

Is it possible to create index for subtype column ‘field2’ via JPA annotations? I can do it with deprecated org.hibernate.annotations.Index, but i don’t understand how to do it with jakarta.persistance.

Thanks!

@Entity
@Inheritance
@Table(name = "tbl_class",
        indexes = {
            @Index(name = "idx_field1", columnList = "field1")
})
class ClassA
{
    @Id
    @GeneratedValue
    private Long id;

    @Column
    private String field1;

    ...
}

@Entity
class ClassB extends ClassA
{ 
    /* @org.hibernate.annotations.Index(name="idx_field2") */
    @Column
    private String field2;

   ...
}

Theoretically you could do this by repeating the @Table annotation:

@Entity
@Inheritance
@Table(name = "tbl_class",
        indexes = {
            @Index(name = "idx_field1", columnList = "field1")
})
class ClassA { ... }

@Entity
@Table(indexes = {
            @Index(name = "idx_field2", columnList = "field2")
})
class ClassB extends ClassA { ... }

But there is an ongoing discussion about whether this should be allowed and what is the right way to do this.

Thanks for the answer. I tried to do this, but unfortunately it doesn’t work.

It seems that the deprecated annotation should exist until a solution appears for JPA.

Something that definitely works is to specify the index on the table of the root class e.g.

@Entity
@Inheritance
@Table(name = "tbl_class",
        indexes = {
            @Index(name = "idx_field1", columnList = "field1"),
            @Index(name = "idx_field2", columnList = "field2")
})
class ClassA { ... }

@Entity
class ClassB extends ClassA { ... }

I agree though, that it feels a bit odd since the field/column is only introduced in the subclass.

1 Like

It works! But that’s really weird.

I hope that JPA will be improved someday.

Thanks for your help!

FTR, the Hibernate ORM team discussed this topic today, and we concluded that defining the @Table annotation on single table inheritance subclasses is wrong. The solution to use is to declare all indexes and other objects on the root class of the inheritance hierarchy:

@Entity
@Inheritance
@Table(name = "tbl_class",
        indexes = {
            @Index(name = "idx_field1", columnList = "field1"),
            @Index(name = "idx_field2", columnList = "field2")
})
class ClassA { ... }

@Entity
class ClassB extends ClassA { ... }