Foreign keys have random number appended when using Hibernate's TABLE_PER_CLASS inheritance

北城以北 提交于 2019-12-25 01:44:05

问题


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();
    }
}


来源:https://stackoverflow.com/questions/6683686/foreign-keys-have-random-number-appended-when-using-hibernates-table-per-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!