Jer*_*meB 6 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)
Run Code Online (Sandbox Code Playgroud)
所以一个节点可以有多个权限,一个权限可以被多个节点引用。
我希望我的课程看起来像:
@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
}
Run Code Online (Sandbox Code Playgroud)
但是注释“@ManyToMany”似乎只能与“@JoinTable”一起使用,在这种情况下它不可用(据我所知)。有谁知道除了修改数据库之外是否还有其他方法?
JPA 不允许这样做,因为它需要外键来引用完整的主键以用于标识目的,并且它可能无法很好地与缓存配合使用。如果可以,我建议使用使用实际主键的关系表切换到更传统的模型。
如果您的提供者允许映射部分 pks(我相信 Hibernate 可以),那么您要做的是制作两个 1:M 映射,每个映射都使用 JoinColumn 而不是 JoinTable,但将 Node->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;
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10846 次 |
| 最近记录: |