【发布时间】:2015-09-27 18:23:51
【问题描述】:
我想通过使用连接表的多对多关联来关联两个实体类 User 和 Unit。然而,这并没有按预期工作。首先,我将简要地向您展示我到目前为止所获得的内容。
数据库:
| User | | UserToUnit | | Unit |
|Id|login|...| |User_Id|Unit_Id| |Id|name|...|
实体用户:
@Entity
@Table(name = "\"User\"")
public class User implements Identifiable {
public User() {
units = new ArrayList<Unit>();
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "guid")
@Column(name = "Id", columnDefinition = "uniqueidentifier")
private String id;
@Transient
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "UserToUnit",
joinColumns = { @JoinColumn(name = "User_Id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "Unit_Id", nullable = false, updatable = false) }
)
private Collection<Unit> units;
[...]
public Collection<Unit> getUnits() {
return units;
}
public void setUnits(Collection<Unit> ous) {
units= ous;
}
}
实体单位:
@Entity
@Table(name = "Unit")
@XmlRootElement
public class Unit implements Identifiable {
public Unit() {
users = new ArrayList<User>();
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "guid")
@Column(name = "Id", columnDefinition = "uniqueidentifier")
private String id;
@Transient
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "units")
private Collection<User> users;
[...]
public Collection<User> getUsers() {
return users;
}
public void setUsers(Collection<User> us) {
users = us;
}
用法:
user.getUnits().add(unit);
unit.getUsers().add(user);
unitDAO.saveOrUpdate(unit);
userDAO.saveOrUpdate(user);
但这不会向 UserToUnit 表添加任何内容。我在这里想念什么? 干杯, 克里斯
【问题讨论】:
标签: hibernate jpa orm many-to-many