Tim
Tim

Reputation: 437

Hibernate: point foreign_key to secondary table

I have three classes:

It has the following hierachy:

public abstract class PlanItem {...}

public class Task extends PlanItem {...}

public class HumanTask extends Task {...}

I am using hibernate to generate two tables: "PlanItem" with all its attributes and "Task" with all its attributes and that of its child.

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class PlanItem {...}

@Entity
@SecondaryTable( name = "Task" )
public class Task extends PlanItem {
    @ElementCollection
    private Set<String> properties;

}

@Entity
@SecondaryTable( name = "Task" )
public class HumanTask extends Task {...}

Hibernate will make an extra table for properties but the foreign_key will point to the "PlanItem" table. How can I let the foreign_key point to the "Task" table?

Upvotes: 0

Views: 2045

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16400

You could try to map it with @ForeignKey

@ElementCollection
@CollectionTable(
  name = "task_properties",
  joinColumns = {
    @JoinColumn(
      name = "task_id"
    )
  },
  foreignKey = @ForeignKey(
    foreignKeyDefinition = "FOREIGN KEY (task_id) REFERENCES Task"
  )
)
private Set<String> properties;

You might need a recent hibernate version because I think being able to specify foreign keys consistently got fixed only partly in 5.0 by HHH-9709 and fully only in 5.2 by HHH-11180.

Upvotes: 1

Related Questions