Search code examples
hibernatejpapolymorphism

How to model a polymorphic relationship in Hibernate 6 for foreign entities with different key types?


I have the following tables (pseudocode):

conversations
  id bigserial

subscribers
  id serial

asset_categories
  id smallserial

requirements
  id serial
  requireable_type text
  requireable_id bigint

For Hibernate I have a MappedSuperclass similar to this:

@MappedSuperclass
public abstract class BaseEntity<T extends Serializable> {
  private T id;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  public T getId() {
    return id;
  }
}

And I have these entities:

Conversation<Long>
Subscriber<Integer>
AssetCategory<Short>
Requirement<Integer>

As you can see, requirements.requireable_type and requirements.requireable_id supports a polymorphic association to the three other types (and bigint of requireable_id covers the id types of the foreign keys).

But I haven't been able to come up with the way to implement this in my Requirement entity.

I've tried an @Any like this in Requirement:

  @Any(fetch = FetchType.LAZY)
  @AnyDiscriminator(DiscriminatorType.STRING)
  @AnyDiscriminatorValues({
    @AnyDiscriminatorValue(discriminator = "subscriber", entity = Subscriber.class),
    @AnyDiscriminatorValue(discriminator = "conversation", entity = Conversation.class),
    @AnyDiscriminatorValue(discriminator = "asset_category", entity = AssetCategory.class)
  })
  @AnyKeyJavaClass(Long.class)
  @Column(name = "requireable_type")
  @JoinColumn(name = "requireable_id")
  public Requireable getRequireable() { return requireable; }  // I have an interface Requireable they all "implement"

But then only the Conversation can be associated and the Requirement persisted. The others fail with errors like java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')

This seems like a normal-enough scenario where the polymorphic relationship is to various tables with different types of identifiers.

So… how do I support this relationship? Should I jettison the @Any annotations and create … something? A CompositeUserType?


Solution

  • I asked in the comment if all the IDs are generated, because I was already thinking that in that case you can manage them all as Long attributes, and let Hibernate store in that the values that are passed from the DB layer. In this case, you won't fall in the case of having a value in an id field that overflows the capacity of the associated column type, during INSERTs.

    I was also thinking if you could use the columnDefinition attribute of the @Column annotation to specify the correct db type (e.g. to support a coherent automatic schema generation for tests), but if the annotation is put on the superclass, then you can't, unless moving them on an overriding method on the subclasses.