spring-boothibernatespring-data-jpa

Table is a subclass in a 'SINGLE_TABLE' hierarchy and may not be annotated '@Table'


I have this old Hibernate table in Spring Boot application:

@Entity
@Table(name = "accounts")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Account {

  @Id
  @Column(name = "id")
  private UUID id;
  ....
}


@Entity
@Table(name = "accounts")
public class CustomerAccount extends Account {

  private String address;
  .....
}

When I run the code I get error:

Caused by: org.hibernate.AnnotationException: Entity 'com.domain.CustomerAccount' is a subclass in a 'SINGLE_TABLE' hierarchy and may not be annotated '@Table' (the root class declares the table mapping for the hierarchy)
    at org.hibernate.boot.model.internal.EntityBinder.handleClassTable(EntityBinder.java:780) ~[hibernate-core-6.6.2.Final.jar:6.6.2.Final]

Do you know how I can fix this issue if possible with minimum changes?


Solution

  • You're using SINGLE_TABLE inheritance, which means all the classes in the hierarchy use the same table.

    In this case, only the parent class should have the @Table annotation. Just remove @Table(name = "accounts") from the subclass.

    So your CustomerAccount class should look like this:

    @Entity
    public class CustomerAccount extends Account {
    
      private String address;
      .....
    }