日期:2014-05-20  浏览次数:20786 次

EJB3 多对多问题,求解
表: Role
@ManyToMany()
@JoinTable(name = "T_Role_Staff")
private Set<Staff> staffs = new HashSet<Staff>();

表: Staff
@ManyToMany(mappedBy = "staffs", cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
private Set<Role> roles = new HashSet<Role>();

客户端代码:
// 添加雇员及权限

Staff s1 = new Staff("danielle");
Staff s2 = new Staff("alven");

Role r1 = new Role("role1");
Role r2 = new Role("role2");

s1.getRoles().add(r1);
s1.getRoles().add(r2);

s2.getRoles().add(r1);
s2.getRoles().add(r2);

这样添加两个雇员进数据库后 , Role 表的数据重复了,要怎么解决啊

------解决方案--------------------
我提供一个我的ManyToMany的配置例子吧,
一个博客,可以有多个附件,反过来,也允许一个附件属于多个博客(共享)
博客表:T_BLOG 主键ID
中间表:T_BLOG_ATTACHMENT( BLOGID,ATTACHMENT_ID) 就2个字段做联合主键
附件表:T_ATTACHMENT 主键ID


@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "T_BLOG_ATTACHMENT", joinColumns = @JoinColumn(name = "BLOG_ID", referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "ATTACHMENT_ID", referencedColumnName = "ID"))
private List<Attachment> attachments;