Same question here, but it didn't help me
我有三张桌子和多对多的连接。在我的JSF应用程序中,我正在尝试添加用户。在我的groups-table中有三个不同的组:admin,customer和user。
我做了什么:
和代码
用户:
public class Users implements Serializable {
@ManyToMany(mappedBy = "usersCollection")
private Collection<Groups> groupsCollection;
组:
public class Groups implements Serializable {
@JoinTable(name = "groups_has_user", joinColumns = {
@JoinColumn(name = "groups_group_id", referencedColumnName = "group_id", nullable = false)}, inverseJoinColumns = {
@JoinColumn(name = "user_username", referencedColumnName = "username", nullable = false)})
@ManyToMany
private Collection<Users> usersCollection;
UsersController-managedBean
// current is type Users
current.setIsCustomer(Boolean.TRUE);
//BalusC!! Why this is not working but the one below is?
//FacesContext facesContext = FacesContext.getCurrentInstance();
//HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
//GroupsController groupsC = (GroupsController)session.getAttribute("groupsController");
FacesContext context = FacesContext.getCurrentInstance();
GroupsController groupsC = (GroupsController) context.getApplication().evaluateExpressionGet(context, "#{groupsController}", GroupsController.class);
// Fetching group number 2, customer
Groups customerGroup = groupsC.getGroupByGroupId(new Integer(2));
List<Users> usersCollection = (List<Users>) customerGroup.getUsersCollection();
usersCollection.add(current);
//List<Groups> groupList = groupsC.getAllGroups();
customerGroup.setUsersCollection(usersCollection);
// Updating the group using GroupsController
groupsC.updateGroup(customerGroup);
//groupList.add(customerGroup);
//current.setGroupsCollection(groupList);
getFacade().create(current);
唯一的方法是我如何获得join-table(groups_has_user)的东西是同时向group-table添加组,但是每个用户都有一条自己的行,我认为这不是目的。很多人问过这个问题,但即使我读过这些内容,我也无法想出来。
谢谢,抱歉! 萨米
答案 0 :(得分:1)
我得到了它的工作。我的代码很乱,我把它清理干净了。我不太清楚为什么更新groups-table会将新用户插入Users-table,但对我来说没问题。起初我更新了groups-table并将用户插入到users-table中,我总是得到一个例外,即已经有pk(用户名是pk)。因此它对用户表进行了两次插入,但现在它完美地工作了。没有更多的行到group-table只是联合表和users-table。
// Add current new user to the customer-group
usersCollection.add(currentUser);
customerGroup.setUsersCollection(usersCollection);
// Updating the group using GroupsController, THIS INSERTS USER TO USERS-table as well!!
groupsC.updateGroup(customerGroup);