0
通常的做法是將同一個實體映射兩次或甚至三次,每次映射處理所需的列的子集。我發現在Hibernate 3.5.1
中,每次在映射同一個表的兩個實體中都存在@ManyToOne
或@OneToMany
時,會創建兩次外鍵。這對MySQL和SQL Server沒有影響,但是Oracle拒絕了第二個創建語句。當映射同一個實體兩次時,Hibernate中的雙重外鍵 -
下面是一個例子:
@Entity
@javax.persistence.SequenceGenerator(name = "SEQ_STORE", sequenceName = "SEQ_ENTITY")
@Table(name = "ENTITIES")
class Entity {
//All columns
//And then.....
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "BRIDGE_TABLE", joinColumns = { @JoinColumn(name = "ENTITY_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
@OrderBy("id DESC")
private Set<Role> roles = new HashSet<Roles>();
}
@Entity
@javax.persistence.SequenceGenerator(name = "SEQ_STORE", sequenceName = "SEQ_ENTITY")
@Table(name = "ENTITIES")
class EntityListItem {
//Only a subset of the previous columns
//And then.....
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "BRIDGE_TABLE", joinColumns = { @JoinColumn(name = "ENTITY_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
@OrderBy("id DESC")
private Set<Role> roles = new HashSet<Roles>();
}
目前,Role
被設計爲不通航到Entity
(否則我估計會有4個的外鍵)。
這裏是由Hibernate所發表的聲明:
create table BRIDGE_TABLE (ENTITY_ID number(19,0) not null, ROLE_ID varchar2(60 char) not null, primary key (ENTITY_ID, ROLE_ID)); //Creates the table
alter table BRIDGE_TABLE add constraint FK47CFB9F0B068EF3F foreign key (ENTITY_ID) references ENTITIES;
alter table BRIDGE_TABLE add constraint FK47CFB9F0B068EF3F foreign key (ENTITY_ID) references ENTITIES;
我不知道這是否是一個Hibernate的bug。我們目前不能移植到Hibernate 4.可以通過代碼修復它,還是需要新的Hibernate版本?