Search code examples
javadatabasehibernatepersistencehibernate-mapping

Hibernate: point foreign_key to secondary table


I have three classes:

  • PlanItem
  • Task
  • HumanTask

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?


Solution

  • 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.