Hibernate多对一外键注释映射

时间:2012-03-05 09:23:54

标签: spring hibernate mapping hibernate-mapping hibernate-annotations

我在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 (....)
);

但是我使用@MapsId注释了assignment.owner_oid,因此在这个连接表中,前两个列总是相同的。此外,我还有更多来自O.class的类,这意味着许多连接表。如何在赋值表上禁用FK约束?

1 个答案:

答案 0 :(得分:0)

你应该移动

...
public Set<Assignment> getAssignments() {
    return assignments;
}

到抽象类,在两个类中都是一样的。

要回答你的问题 - 在你这样做之后你可以将你的InheritanceType改为JOINED(或者说是SINGLE_TABLE,但是你说你有很多其他的子类因此它不合适) - 那么你将只有一个包含owner_oid列的表从作业中引用。