Hibernate generates incorrect foreign key constraint for single table inheritance in OneToMany

Viewed 35

I have single-table inheritance:

@Entity
@Table(name = "items")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "fruit_type", discriminatorType = DiscriminatorType.STRING)
public abstract class Item<T extends Base> extends Base {

    @JsonIgnore
    @JoinColumn(name = "fruit_id")
    @ManyToOne(fetch = FetchType.LAZY)
    public T getFruit();

with concrete subclass:

@Entity
@DiscriminatorValue("banana")
public class BananaItem extends Item<Banana> {

and another:

@Entity
@DiscriminatorValue("orange")
public class OrangeItem extends Item<Orange> {

and the two fruit classes hold collections of these items, like in Banana:

@OneToMany(mappedBy = "fruit", cascade = CascadeType.ALL, orphanRemoval = true)
private List<BananaItem> bananaItems;

and in Orange:

@OneToMany(mappedBy = "fruit", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrangeItem> orangeItems;

but now, in a test, when I go to make an innocent Banana holding some bananaItems (who have had bananaItem.setFruit(banana) called on them), I get this bizarre FK constraint violation from Hibernate's generated schema used in tests:

Referential integrity constraint violation: "FK9QL9Y1RJG59996CUD9NAVCN80: PUBLIC.ITEMS FOREIGN KEY(PARENT_ID) REFERENCES PUBLIC.ORANGES(ID)

for some reason Hibernate thinks it should have OrangeItems, even though I'm saving a Banana with BananaItems in it! I'm at my wit's end on this. If I modify the @JoinColumn for getFruit() to use foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT) then the error goes away, but that feels rather hacky and I could be missing some other subtle problem.

0 Answers
Related