0
我在Spring 3.1中使用了Hibernate 4,並且從這個映射中生成的外鍵約束有問題。休眠多對一的外鍵註釋映射
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class O {
private String oid;
@Id
@GeneratedValue(generator = "OidGenerator")
@GenericGenerator(name = "OidGenerator", strategy = "com.evolveum.midpoint.repo.sql.OidGenerator")
@Column(unique = true, nullable = false, updatable = false, length = 36)
public String getOid() {
return oid;
}
...other getters and setters
}
@Entity
public class Role extends O {
private Set<Assignment> assignments;
@OneToMany(mappedBy = "owner")
@Cascade({org.hibernate.annotations.CascadeType.ALL})
public Set<Assignment> getAssignments() {
return assignments;
}
...other getters and setters
}
@Entity
public class User extends O {
private Set<Assignment> assignments;
@OneToMany(mappedBy = "owner")
@Cascade({org.hibernate.annotations.CascadeType.ALL})
public Set<Assignment> getAssignments() {
return assignments;
}
...other getters and setters
}
@Entity
public class Assignment extends IdentifiableContainer {
private O owner;
private Long id;
@Id
@MapsId("oid")
@ManyToOne
public O getOwner() {
return owner;
}
@Id
@GeneratedValue(generator = "ContainerIdGenerator")
@GenericGenerator(name = "ContainerIdGenerator", strategy = "com.evolveum.midpoint.repo.sql.ContainerIdGenerator")
@Column(nullable = true, updatable = true)
public Long getId() {
return id;
}
...other getters and setters
}
這將產生模式是這樣的...
create table Assignment (
id bigint not null,
owner_oid varchar(36) not null,
primary key (owner_oid, id)
);
create table Role (
oid varchar(36) not null unique,
primary key (oid)
);
create table User (
oid varchar(36) not null unique,
primary key (oid)
);
alter table Assignment
add constraint FKB3FD62ED72781986
foreign key (owner_oid)
references User;
alter table Assignment
add constraint FKB3FD62ED7276AE31
foreign key (owner_oid)
references Role;
上Assignment.owner_oid兩個約束不應該存在。因爲他們,我無法保存角色/用戶的任務。我想到了使用連接表的其他解決方案,但我看起來過於尷尬。加入表看起來像
create table Role_Assignment (
role_oid varchar(36) ...
assignment_oid varchar(36) ...
assignment_id bigint ...
primary key (....)
);
但我因此在這種連接表前兩colums是始終不變的assignment.owner_oid註解爲@MapsId。此外,我還有更多類從O.class擴展,這意味着許多連接表。如何禁用賦值表上的FK約束?
我無法移動getAssignments()方法。但正如你所說,我會將InheritanceType更改爲JOINED,並在getAssignments()方法中使用'@ForeignKey(「none」)'註釋來禁用用戶和角色的FK約束。因此,hibernate只會生成一個引用O的FK約束,這對我來說確實很好。 – viliam 2012-03-05 15:30:41
爲什麼你不能移動getAssignments()?也許你可以爲用戶和角色創建超類? – 2012-03-05 17:11:06
類的層次結構是固定的,我不能改變它會破壞其他的東西。我只需要堅持下去...不知何故:)但我修復了由休眠生成的FK。感謝您的想法。 – viliam 2012-03-06 17:40:58