没有连接表的多对多关联

时间:2014-07-29 11:52:27

标签: java sql hibernate jpa jpa-2.0

我想在以下(简化)数据库中应用JPA:

NODE                         AUTHORITY
-----                        ----------
idNode int                   idAuthorities int
nameNode varchar(50)         person varchar(255)
idAuthorities int            rank int
PRIMARY KEY (idNode)         PRIMARY KEY (idAuthorities, rank)
FOREIGN KEY (idAuthorites)

因此,一个节点可以拥有多个权限,并且多个节点可以引用一个权限。

我希望我的课程看起来像:

@Entity
@Table(name="NODE")
public class Node {

    private Integer id;
    private String nameNode;
    private Set<Authority> authorities;

    // ... getter and setter normaly annoted for "id" and "nameNode"

    @ManyToMany
    public Set<Authority> getAuthorities(){
        return authorities;
    }
    // ... setter ...

}

@Entity
@Table(name="AUTHORITY")
public class Authority {

    private AuthorityPK pk;
    private String person;
    privat Set<Node> nodes;

    // ... getter and setter normaly annoted for "person"

    @Id
    public AuthorityPK getPk(){
        return this.pk
    }
    // ... setter ...

    @ManyToMany
    public Set<Node> getNodes(){
        return nodes;
    }
    // ... setter ...

}

@Embeddable
public class AuthorityPK implements Serializable {
    private Integer idAuthorities;
    private Integer rankAuthorities;

    // override of equals and hashCode
}

但注释&#34; @ ManyToMany&#34;似乎只能用于&#34; @ JoinTable&#34;,在这种情况下,这是不可用的(据我所知)。 有谁知道修改数据库是否有办法?

1 个答案:

答案 0 :(得分:2)

JPA不允许这样做,因为它需要外键来引用完整的主键以用于身份识别,并且它可能无法与缓存一起使用。如果可以,我建议使用使用实际主键的关系表切换到更传统的模型。

如果您的提供者允许映射部分pks(我相信Hibernate会这样做),那么你要做的是使用JoinColumn而不是JoinTable制作两个1:M映射,但是将Node-&gt; Authority上的那个映射为insertable = false ,updatable = false

例如:

public class Node {
    @Id
    private Integer id;
    private String nameNode;
    @OneToMany
    @JoinColumn(name = "idAuthorites", referencedColumnName = "idAuthorites", insertable=false, updatable=false)
    private Set<Authority> authorities;
    ...

public class Authority {
    @Id
    private AuthorityPK pk;
    private String person;
    @OneToMany
    @JoinColumn(name = "idAuthorites", referencedColumnName = "idAuthorites")
    private Set<Node> nodes;
    ...