Home > Net >  Reading different entities from same Spring JPA repository using Hibernate SINGLE_TABLE strategy
Reading different entities from same Spring JPA repository using Hibernate SINGLE_TABLE strategy

Time:01-21

I have base abstract class and 2 entities within same table, using descriminator-type inheritance in hibernate.

@MappedSuperclass()
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type", discriminatorType = DiscriminatorType.INTEGER)
public abstract class Relation {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(columnDefinition = "bigint unsigned", name = "id")
    public long id;
    @Enumerated(EnumType.ORDINAL)
    RelationType type;
}

@Table(name = "relation")
@Entity
@DiscriminatorValue("0")
public class Ban extends Relation {
    // ...
    public RelationType type = RelationType.BAN;
}

Same for second entity but with @DiscriminatorValue("1").

The problem is: when reading these entities via single repository, SQL doesn't contain discriminator value in 'where' condition.

Separate repository for every entity is a must?

CodePudding user response:

It is not a must to use a separate repository for every entity, but it may be necessary in your case depending on how you want to retrieve the data. If you want to retrieve only the rows of a particular child class, you will need to include the discriminator column in the 'where' condition of the SQL query. One way to do this would be to create separate repositories for each child class, each with their own query methods that include the appropriate discriminator value in the 'where' condition.

Alternatively, you can use Hibernate's criteria API or query by example (QBE) to filter the results based on the discriminator value. This way you can use a single repository for all the entities and filter them based on discriminator value.

CodePudding user response:

You have not explained why you want to restrict by the discriminator column in cases where Hibernate judges it to be unnecessary, so it's pretty hard to answer your question definitively.

But there are a couple of things Hibernate provides:

  • The annotation @DiscriminatorOptions(force=true), usually used in cases where the table contains extra data not mapped to an entity class.
  • The HQL type() function for which you may find examples here in the documentation.
  • Related