title: Using Index annotation on superclass with Hibernate
body: <p>I have an abstract superclass which every Entity on my domain is a subclass of it.</p>
  
  <p>Using DB schema generation, I want to create an Index for each Entity, on a field on the superclass, and without using the Table annotation on every subclass.</p>
  
  <p>My superclass</p>
  
  <pre class="lang-java prettyprint-override"><code>    @MappedSuperclass
      public abstract class BaseEntity {
  
          @Id
          @GeneratedValue(strategy = SEQUENCE)
          private Long surrogateId;
  
          @Index(name="id_index") // Every subclass should inherit this index, with its own name
          @Column(unique = true, updatable = false, nullable = false)
          private UUID id = UUID.randomUUID();
  </code></pre>
  
  <p>An example of subclass</p>
  
  <pre class="lang-java prettyprint-override"><code>    @Entity
      public class Customer extends BaseEntity {
          ...
      }
  </code></pre>
  
  <p>I tried so far:</p>
  
  <ul>
  <li><p>use the <strong>Table</strong> annotation with @Index on the superclass, but Hibernate
  doesn't seem to use that annotation if it is not marked with @Entity. 
  For example
  <code>@Table(indexes = {@Index(name="index_id", columnList = "id")})</code> 
  No SQL statements are generated.</p></li>
  <li><p>use the <strong>deprecated @Index</strong> annotation with a name "id_index", but only one index
  is created on startup (the db raises an error that this index already
  exists for other entities). Some generated SQL statements:</p></li>
  </ul>
  
  <pre><code>    Hibernate: create index id_index on "customer" ("id")
  
      Hibernate: create index id_index on "user" ("id")
  
      2020-02-15 17:47:26,620 WARN  o.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl    - GenerationTarget encountered exception accepting command : Error executing DDL "create index id_index on "customer" ("id")" via JDBC Statement
      org.postgresql.util.PSQLException: ERROR: relation "id_index" already exists
  </code></pre>
  
  <p>Any ideas on how to do this without too much code duplication?</p>
  
  <p>Thanks</p>