beginner_
beginner_

Reputation: 7622

hibernate-JPA, ManyToOne and TablePerClass or Joined: creates wrong foreign key

I have these 2 abstract classes:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name="compound")
public abstract class Compound<T extends Containable {


    @OneToMany(fetch = FetchType.EAGER, mappedBy="compound",
        targetEntity=Containable.class, cascade = CascadeType.ALL)      
    private Set<T> containables = new HashSet<>();
}

@Entity 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name="containable")
public abstract class Containable<T extends Compound> {     

    @ManyToOne(optional=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private T compound;
}

In my Tests I have 2 implementations of each, TestCompound and TestContainable as one pair and RegistrationCompound and Batch as the other pair. (eg. public class TesCompound extends Compound<TestContainable> and public class RegistrationCompound extends Compound<Batch>).

TABLE_PER_CLASS for both hierarchies

The issue I'm facing is that hibernate create a foreign key constraint from test_containable table to registration_compound instead to test_compound. It does nto seem to get the generic relationship.

JOINED for both hierarchies (ignoring downsides in my case)

Here it is required that Compound and Containable are concrete classes (not abstract) Else similar issue. hibernate creates foreign key constraint from containable -> compound (expected) but also foreign key constraint from containable -> registration_compound (unexpected). I have no idea why this is created? even more confusing is the fact that there is no such constraint from containable -> test_compound

All in all very confusing. Will try single_table but that is the least desired option...

Upvotes: 1

Views: 833

Answers (1)

beginner_
beginner_

Reputation: 7622

This was caused by a wrong mapping.

@ManyToOne(optional=true, fetch = FetchType.EAGER, cascade = CascadeType.ALL,
    targetEntity = Compound.class)
private T compound;

targetEntity was missing and for some reason hibernate just assumed that 1 of the implementation is the target. Kind of annoying...

Upvotes: 2

Related Questions