Foreign keys have random number appended when usin

2019-09-18 15:44发布

问题:

I currently have the following in my domain model:

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Entity
abstract class Item {
    @ManyToOne
    @ForeignKey(name="FK_ITEM_ORG")
    @JoinColumn(name="ORG_ID")
    private Organization org
}

@Table(name = "ItemA")
public class ItemA extends Item {}

@Table(name = "ItemB")
public class ItemA extends Item {}

Hibernate's HBM2DDL creates 2 tables for this mapping: ItemA and ItemB. Both have the ORG_ID column and a foreign key to the Organization table. However, each foreign key has a random number appended (ie FK_ITEM_ORG98343). How can I specify what foreign key each table uses? For example, I want to have FK_ITEMA_ORG and FK_ITEMB_ORG.

Update

Please also see the follow-on question: Is the ForeignKey annotation only used by HBM2DDL to generate the schema?

回答1:

Unfortunately, you have to remove annotation from field in main class and move it to method in each children with providing FK name.

Something like that:

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Entity
public abstract class Item {
    private Organization  org;
    public Organization getOrg() {
        return org;
    }

}

@Entity
@Table(name = "ItemA")
public class ItemA extends Item {
    @ManyToOne
    @JoinColumn(name="ORG_ID")
    @ForeignKey(name="FK_ITEM_ORG_1")
    public Organization getOrg(){
        return super.getOrg();
    }
}


public class ItemB extends Item{
    @ManyToOne
    @JoinColumn(name="ORG_ID")
    @ForeignKey(name="FK_ITEM_ORG_2")
    public Organization getOrg(){
        return super.getOrg();
    }
}