How do you map two abstract InheritanceType.TABLE_PER_CLASS entities with a OneToMany relationship?

I’m using Hibernate with Spring Boot and JPA, and have a business requirement to retrieve and combine in to a single paged response data that is stored in four different tables in the DB.

Let’s call the first two tables “tblCredits”, containing Credits, and “tblDebits”, containing Debits. For our purposes, those two tables are IDENTICAL – same column names, same column types, same ID fields, everything. And my endpoint is supposed to be able to return a combined list of both Credits and Debits, with the ability to search/sort by any/all of the fields being returned, and with paging.

If I controlled that DB, I would simply merge the two tables in to a single table, or create a view or stored proc which did that for me, but this is a legacy DB used by other applications which I can’t modify in any way, so that’s not an option.

If I didn’t have to sort and page, I could just create two completely independent entities, create a separate Spring Data JPA repository for each entity, query the two repositories separately, and then just combine the results in my own code. But paging the combined results especially would get very hairy, I don’t want to have to implement the merged paging logic myself unless I absolutely have to. Ideally I should be able to get JPA to handle all of that for me out-of-the-box.

I have been able achieve this first step for these first two tables using an abstract class declared as an Entity with InheritanceType.TABLE_PER_CLASS, like this:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here 
...
*/
}

And then two concrete classes which extend that abstract entity and simply specify the two different table mappings, have no class-specific properties or column mappings at all:

@Entity
@Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {
//Literally nothing inside this class
}

@Entity
@Table(name = "tblDebits")
public final class Debit extends AbstractCreditDebitEntity {
//Literally nothing inside this class
}

So far so good, this works great, I am able to create a Spring JPA Repository on the AbstractCreditDebitEntity entity, under the hood that generates a union query on the two tables, and I am able to get back records from both tables in a single query, with appropriate paging and sorting. (The performance issues around union queries don’t concern me at the moment.)

However, where I’m getting tripped up is on the next step, when I incorporate the additional two tables. tblCredits has a one-to-many relationship to tblCreditLineItems, and tblDebits has a one-to-many relationship to tblDebitLineItems. Again, tblCreditLineItems and tblDebitLineItems are IDENTICAL tables, from our perspective – same column names, same column types, same ID fields, everything.

So I can follow the same pattern as before for those sub-entities:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitLineItemEntity {
/* literally all my properties and ID and column mappings here 
...
*/
}
@Entity
@Table(name = "tblCreditLineItems")
public final class CreditLineItem extends AbstractCreditDebitLineItemEntity {
//Literally nothing inside this class
}

@Entity
@Table(name = "tblDebitLineItems")
public final class DebitLineItem extends AbstractCreditDebitLineItemEntity {
//Literally nothing inside this class
}

But now I need to create the mappings between the Credit/Debit entities and CreditLineItem/DebitLineItem entities. And this is where I’m struggling. Because I need to be able to filter which specific Credit/Debit entities I return based on the values of properties inside their associated CreditLineItem/DebitLineItem entities, I need a bidirectional mapping between the two entities, and I’ve been unable to get that working successfully.

Here’s how far I’ve gotten so far. First the three Credit/Debit entities with the OneToMany mapping to their associated CreditLineItem/DebitLineItem entities:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here 
...
*/
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName"
  )
  public abstract List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems();

  public abstract void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items);

}
@Entity
@Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {

  private List<CreditLineItem> creditDebitLineItems;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = CreditLineItem.class)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName"
  )
  @Override
  public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
    return Optional.ofNullable(creditDebitLineItems).stream()
        .flatMap(List::stream)
        .filter(value -> AbstractCreditDebitLineItemEntity.class.isAssignableFrom(value.getClass()))
        .map(AbstractCreditDebitLineItemEntity.class::cast)
        .collect(Collectors.toList());
  }

  @Override
  public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
    creditDebitLineItems =  Optional.ofNullable(items).stream()
      .flatMap(List::stream)
      .filter(value -> CreditLineItem.class.isAssignableFrom(value.getClass()))
      .map(CreditLineItem.class::cast)
      .collect(Collectors.toList());
  }

}

@Entity
@Table(name = "tblDebits")
public final class Debit extends AbstractCreditDebitEntity {
  private List<DebitLineItem> creditDebitLineItems;

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = DebitLineItem.class)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName"
  )
  @Override
  public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
    return Optional.ofNullable(creditDebitLineItems).stream()
        .flatMap(List::stream)
        .filter(value -> AbstractCreditDebitLineItemEntity.class.isAssignableFrom(value.getClass()))
        .map(AbstractCreditDebitLineItemEntity.class::cast)
        .collect(Collectors.toList());
  }

  @Override
  public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
    creditDebitLineItems =  Optional.ofNullable(items).stream()
      .flatMap(List::stream)
      .filter(value -> DebitLineItem.class.isAssignableFrom(value.getClass()))
      .map(DebitLineItem.class::cast)
      .collect(Collectors.toList());

  }
}

And then the three CreditLineItem/DebitLineItem entities with their ManyToOne mappings back to the Credit/Debit entities:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitLineItemEntity {
/* literally all my properties and ID and column mappings here 
...
*/
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName",
      updatable = false,
      insertable = false)
  public abstract AbstractCreditDebitEntity getCreditDebit();

  public abstract void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity);
}
@Entity
@Table(name = "tblCreditLineItems")
public final class CreditLineItem extends AbstractCreditDebitLineItemEntity {

    private Credit creditDebit;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName",
      updatable = false,
      insertable = false)
 @Override
  public Credit getCreditDebit() {
    return creditDebit;
  }

  @Override
  public void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity) {
    creditDebit =
        Optional.ofNullable(creditDebitEntity)
            .filter(value -> Credit.class.isAssignableFrom(value.getClass()))
            .map(Credit.class::cast)
            .orElse(throw new RuntimeException());
  }
}

@Entity
@Table(name = "tblDebitLineItems")
public final class DebitLineItem extends AbstractCreditDebitLineItemEntity {
    private Debit creditDebit;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName",
      updatable = false,
      insertable = false)
 @Override
  public Debit getCreditDebit() {
    return creditDebit;
  }

  @Override
  public void setCreditDebit(AbstractCreditDebitEntity creditDebitEntity) {
    creditDebit =
        Optional.ofNullable(creditDebitEntity)
            .filter(value -> Debit.class.isAssignableFrom(value.getClass()))
            .map(Debit.class::cast)
            .orElse(throw new RuntimeException());
  }
}

This code compiles, however… when in my automated tests I try to persist one of my Credit entities (I use a simple H2 database for my automated tests), I get the following error:

2021-04-02 13:53:52 [main] DEBUG org.hibernate.SQL T: S: - update AbstractCreditDebitLineItemEntity set MyIdColumnName=? where ID=?
2021-04-02 13:53:52 [main] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper T: S: - could not prepare statement [update AbstractCreditDebitLineItemEntity set MyIdColumnName=? where ID=?]
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "ABSTRACTCREDITDEBITLINEITEMENTITY" does not exist

It appears to be trying to persist based on the @OneToMany mapping from my AbstractCreditDebitEntity class to my AbstractCreditDebitLineItemEntity. Which, since it’s an abstract class with InheritanceType.TABLE_PER_CLASS, has no table specified for it, so it assumes the table it needs to persist to has the same name as the class.

What I wanted to happen here is for the @OneToMany mapping on the concrete getter in the Credit subclass, which specifies its targetEntity as the concrete CreditLineItem.class, to essentially override/replace the @OneToMany mapping on its parent abstract class. But it seems the mapping on the concrete class gets completely ignored?

I could remove the @OneToMany mapping from the AbstractCreditDebitEntity class entirely, and only define that mapping in the two concrete Credit/Debit entities that extend it. That makes the persistence error go away, and 90% of my test cases pass… but in that case when I try to filter or sort the results coming back from the combined AbstractCreditDebitEntity Spring Data JPA repository based on one of the fields that only exists in the CreditLineItem/DebitLineItem sub-entity, the query fails due to the AbstractCreditDebitEntity no longer having any mapping to the AbstractCreditDebitLineItemEntity.

Is there any good way of resolving this problem, so that the OneToMany mapping from AbstractCreditDebitEntity to AbstractCreditDebitLineItemEntity still exists, but the knowledge that the Credit entity maps specifically to the CreditLineItem entity and the Debit entity maps specifically to the DebitLineItem entity is also maintained?

Answer

After a lot of experimentation, I found something that works for me.

Basically, rather than try to override the OneToMany mapping in the abstract entity class with the OneToMany mappings in the concrete entities, I had to make them completely separate mappings to completely different properties. Which means my concrete entities have two different collections of AbstractCreditDebitLineItemEntity, and some AbstractCreditDebitLineItemEntity objects will appear twice, in both collections. A bit wasteful in terms of memory/computation, but I’m okay with that, it works!

So here’s what I ended up with:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractCreditDebitEntity {
/* literally all my properties and ID and column mappings here 
...
*/

  private List<AbstractCreditDebitLineItemEntity> creditDebitLineItems;

  @OneToMany(fetch = FetchType.LAZY, targetEntity = AbstractCreditDebitLineItemEntity.class)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName",
      updatable = false,
      insertable = false
  )
  public List<AbstractCreditDebitLineItemEntity> getCreditDebitLineItems() {
    return creditDebitLineItems;
  }

  public void setCreditDebitLineItems(List<AbstractCreditDebitLineItemEntity> items) {
    creditDebitLineItems = items;
  }

}
@Entity
@Table(name = "tblCredits")
public final class Credit extends AbstractCreditDebitEntity {

  private List<CreditLineItem> creditLineItems;

  @OneToMany(cascade = CascadeType.ALL, targetEntity = CreditLineItem.class)
  @LazyCollection(LazyCollectionOption.FALSE)
  @JoinColumn(
      name = "MyIdColumnName",
      referencedColumnName = "MyIdColumnName"
  )
  public List<CreditLineItem> getCreditLineItems() {
    return creditLineItems;
  }

  @Override
  public void setCreditDebitLineItems(List<CreditLineItem> items) {
    creditLineItems =  items;
  }

}

With the exact same pattern repeated for the Debit entity.

This allows me to both:

  1. persist, using the OneToMany mappings from the concrete Credit and Debit entities to the concrete CreditLineItem and DebitLineItem entities; and

  2. do finds on the Spring Data JPA repository of AbstractCreditDebitEntity, using the the completely separate OneToMany mapping from that abstract entity to the AbstractCreditDebitLineItemEntity.

Not as clean as if I’d been able to override the OneToMany mapping in the abstract parent class with a more specific OneToMany mapping in the concrete child classes… but as I said, it works!

(The answer on this issue helped me know I needed to replace fetchType=FetchType.EAGER on my concrete OneToMany mappings with @LazyCollection(LazyCollectionOption.FALSE): Hibernate throws MultipleBagFetchException – cannot simultaneously fetch multiple bags)