休眠多对一的外键注释映射
问题描述:
我在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约束?
答
你应该将
...
public Set<Assignment> getAssignments() {
return assignments;
}
抽象类,它在这两个类是相同的。
为了回答你的问题 - 做完这些之后,你可以将你的InheritanceType改为JOINED(或SINGLE_TABLE,但你说你有很多其他的子类,因此它不合适) - 那么你将只有一个拥有owner_oid列的表应该从转让中引用。
我无法移动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